sna*_*rio 0 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");
}
Run Code Online (Sandbox Code Playgroud)
C5-driver.c
Run Code Online (Sandbox Code Playgroud)#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,如上所示.谢谢〜
反向函数调用cons来分配内存,然后它覆盖lst3指针.内存泄漏是lst3被覆盖,这使得无法恢复该内存.
你可能应该创建一个像struct node *lst3_reverse和的新变量lst3_reverse = reverse(lst3).然后你可以安全地做free_list(lst3)并free_list(lst3_reverse)释放记忆.