0

我对指针和内存模型相当陌生,所以如果这很明显,请原谅,但我正在编写一个程序来测试一个反转列表的函数反转。无论如何,我将它放在三个文件中,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-驱动程序.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_list 。

谢谢~

4

1 回答 1

5

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

您可能应该创建一个新变量,例如struct node *lst3_reverseand lst3_reverse = reverse(lst3)。然后你可以安全地做free_list(lst3)free_list(lst3_reverse)释放内存。

于 2013-01-16T20:43:36.370 回答