【发布时间】:2021-07-09 01:26:16
【问题描述】:
在 C 中,我试图释放单链表中的所有内存,其结构为:
typedef struct node {
char *data;
int weight;
struct node *next;
} Node;
最后一个元素的下一个字段为NULL。每个节点及其数据字段都是动态分配的。到目前为止,我的功能是:
void free_list(Node *const list) {
Node *current = list;
Node *temp;
while (current != NULL) {
temp = current;
current = current->next;
free(temp->data);
free(temp);
}
}
当我在 valgrind 上运行我的一项测试时,我可以看到所有堆块都被释放,所以肯定没有内存泄漏,这是目标。然而,valgrind 给我一个Invalid free() 错误,我不知道为什么。奇怪的是,当我删除free(temp) 行时,此错误消失了,但我现在正在泄漏内存。所以这条线既是必要的,也是有问题的。我哪里出错了?
添加更多代码以制作可重现的示例。
节点被添加到列表中:
unsigned int add(Node *const head, const char new_data[], unsigned int weight) {
Node *current = head;
Node *new_node = malloc(sizeof(Node));
char *new_data_copy = malloc(strlen(new_data) + 1);
strcpy(new_data_copy, new_data);
/* this loop moves the current pointer to the point where the new element
should be inserted, since this is a sorted list. */
while (current->next != NULL && current->next->weight < weight) {
current = current->next;
}
new_node->data = new_data_copy;
new_node->weight = weight;
new_node->next = current->next
current->next = new_node;
return 1;
}
列表总是在我调用任何东西之前初始化,数据、权重和下一个字段的值为NULL、-1和NULL。
如您所见,列表是从最低重量到最高重量的顺序。我可能需要解决更多错误,这就是为什么我试图减少问题以将我的特定问题与 valgrind 隔离开来。
编辑:valgrind 向我展示了 12 个分配和 13 个释放,所以某处有一个游离的游离...
编辑 2:
头部是如何产生的?主要是声明Node head,然后调用initialize(&head)。
void initialize(Node *const head) {
head->data = NULL
head->weight = -1;
head->next = NULL
}
一个主要的
#include "structure.h"
int main(void) {
Node head;
char *data[] = {"A","B","C","D","E","F"};
int weight[] = {1, 2, 3, 4, 5, 6};
int i;
initialize(&head);
for (i = 0; i< 6; i++) {
add(&head, data[i], weight[i]);
}
free_list(&head);
return 0;
}
【问题讨论】:
-
以后,在添加详细信息时,请编辑您现有的问题,而不是删除它以发布新问题。如果它已关闭,其他用户可以在您编辑后重新打开它。但是删除和重新发布问题以绕过关闭可能会被禁止。
-
但这不是minimal reproducible example,直到有一个代码块我可以粘贴到文件中,编译,运行,然后查看错误。这意味着
main函数、标题等,以及必要的输入文件(如果需要)。 -
明白了
-
大胆猜测:头节点是如何创建的?
free_list函数假定它是malloced:是吗? -
您正在调用
free_list(&head),最终调用free(&head),但head已分配在堆栈上。
标签: c valgrind free singly-linked-list