Val差伦告诉我,代码中的特定行会产生内存泄漏,但是当查看该行时,它似乎甚至无法创建一个。
我正在处理这个非常简单的链接列表结构列表。h:
typedef struct _linekd_list{
void* object;
struct _linked_list* next;
}linked_list;下面是list.c中初始化列表的方式:
linked_list* newlist(){
linked_list * list = malloc(sizeof(linked_list));
list->next = NULL; //As a flag, that there is no next element
list->object = NULL;
return list;
}我的队列工作得很好,第一个linked_list的第一个对象总是NULL,第一个对象存储在下一个linked_list中。
下面是内存泄漏的地方:
int list_add(void* new_object, linked_list* list){
while(list->next != NULL) { //First go to the end of the queue
list = list->next;
}
list->next = malloc(sizeof(linked_list)); //Vangrind says there is a leak
list->next->next = NULL; //Set the next list-object to NULL (acts like a flag)
list->next->object = new_object; //And now store the pointer of the actual object
if(list->next->object == new_object) {
return 0;
} else {
return 1;
}
return 0;
}这就是瓦伦丁告诉我的:
==33369== 16 bytes in 1 blocks are definitely lost in loss record 1 of 3
==33369== at 0x483B7F3: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)
==33369== by 0x402219: list_add (list.c:11)
==33369== by 0x4012D0: main (test_list.c:38)
==33369== 下面是递归释放列表的函数(没有检测到内存泄漏):
void free_list(linked_list* list){
if(list->next != NULL) {
free_list(list->next);
free(list);
}
}发布于 2022-06-16 13:49:34
您不能释放列表中的最后一个节点。
如果free_list是NULL,则什么也不做。但你不想什么都不做。您不想递归,但仍然需要释放节点。因此,将对free的调用移出条件,或更改测试以检查list本身是否为NULL
https://stackoverflow.com/questions/72646267
复制相似问题