为什么我的C反转列表函数内存泄漏?
我对指针和内存模型相当陌生,所以如果这是显而易见的,请原谅,但我正在编写一个程序来测试反转列表的函数反转。总之,我有三个文件,C5.c、C5 driver.c和C5.h。按顺序排列如下:为什么我的C反转列表函数内存泄漏?,c,memory,malloc,free,memory-leaks,C,Memory,Malloc,Free,Memory Leaks,我对指针和内存模型相当陌生,所以如果这是显而易见的,请原谅,但我正在编写一个程序来测试反转列表的函数反转。总之,我有三个文件,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(stru
#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");
}
然而,XCode告诉我有内存泄漏
我假设是在使用cons之后,但是我尝试创建了一个新的struct节点*ans=new
和free(new);返回ans;但这不起作用。我也尝试了免费列表,如你所见
谢谢~反向函数调用cons分配内存,然后覆盖lst3指针。内存泄漏是lst3被覆盖,这使得无法恢复该内存
您可能应该创建一个新变量,如
struct node*lst3\u reverse
和lst3\u reverse=reverse(lst3)
。然后您可以安全地执行free\u list(lst3)
和free\u list(lst3\u reverse)
来释放内存。reverse函数调用分配内存的cons,然后覆盖lst3指针。内存泄漏是lst3被覆盖,这使得无法恢复该内存
您可能应该创建一个新变量,如struct node*lst3\u reverse
和lst3\u reverse=reverse(lst3)
。然后您可以安全地执行free\u list(lst3)
和free\u list(lst3\u reverse)
来释放内存
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); }