为什么内存在我的C反向列表功能中泄露?

时间:2013-01-16 20:39:01

标签: c memory malloc free memory-leaks

我对Pointers和内存模型还不熟悉,如果这很明显,请原谅我,但我正在编写一个程序来测试反转列表的函数反转。无论如何,我有三个文件,C5.c,C5-driver.c和C5.h.他们按顺序在这里:

#include "C5.h"
#include <stdlib.h>
#include <stdio.h>

struct node *cons(int fst, struct node *rst) {
    struct node *new = malloc(sizeof(struct node));
    if (new == NULL) {
        printf("cons: out of memory\n");
        abort();
    }
    (*new).first = fst; /* same as (*new).first = fst */
    (*new).rest = rst;
    return new;
}

struct node *reverse(struct node *lst) {
    struct node *ans = NULL;
    while (lst != NULL) {
        ans = cons((*lst).first, ans);
        lst = (*lst).rest;
    }    
    return ans;
}

void free_list(struct node *lst) {
    struct node *p;
    while (lst != NULL) {
        p = lst->rest;
        free(lst);
        lst = p;
    }
}

void print_list(struct node *lst) {
    printf("( "); 
    while (lst != NULL) {
        printf("%d ", (*lst).first);
        lst = (*lst).rest;
    }
    printf(")\n");
}

C5-driver.c

#include <stdlib.h>
#include <stdio.h>
#include "C5.h"

int main() {
    struct node *lst1 = cons(5, NULL);
    struct node *lst2 = cons(3, lst1);
    struct node *lst3 = cons(1, lst2);
    print_list(lst3);
    lst3 = reverse(lst3);
    print_list(lst3);
    free_list(lst3);
}

C5.h

struct node { int first; struct node *rest; }; struct node *cons(int ,struct node *); struct node *reverse(struct node *); void print_list(struct node *); void free_list(struct node *);

然而,我被XCode告知存在内存泄漏。

我假设它在使用cons之后但是我尝试创建一个新的struct node *ans = new和free(new);带回报;但这不起作用。我已经尝试了free_list,如上所示。

感谢〜

1 个答案:

答案 0 :(得分:5)

反向函数调用cons来分配内存,然后它覆盖lst3指针。内存泄漏是lst3被覆盖,这使得无法恢复该内存。

您应该制作一个新变量,例如struct node *lst3_reverselst3_reverse = reverse(lst3)。然后,您可以放心地free_list(lst3)free_list(lst3_reverse)释放内存。