c - 释放单链表的内存时出现无效的 free() 错误
问题描述
在 C 中,我试图释放单链表中的所有内存,其结构是:
typedef struct node {
char *data;
int weight;
struct node *next;
} Node;
最后一个元素的 next 字段为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 个 allocs 和 13 个 frees,所以某处有一个流浪的 free ......
编辑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;
}
解决方案
free
仅适用于在堆上分配的东西malloc
。如果你在堆栈上分配一些东西,它的内存就会为你管理。
大概发生了这样的事情。
// The first Node is allocated on the stack
Node list = { .data="test", .weight=23 };
// The rest are heap allocated.
add(list, "new", 42);
// free_list calls free() on all of them
free_list(list);
您可以通过提取代码以从add
.
Node *new_node( const char *data, int weight ) {
Node *node = malloc(sizeof(Node));
node->data = strdup(data);
node->weight = weight;
return node;
}
然后这可以用来初始化列表,也可以用来传递给add。这使得确保每个节点都在堆上分配更容易。它使添加更有用,它可以添加任何现有节点。
Node *add(Node *current, Node *new_node) {
while (current->next != NULL && current->next->weight < weight) {
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
// Might be useful to know where the node was added.
return current;
}
Node *list = new_node("test", 23);
add(list, new_node("new", 42));
free_list(list);
(我正在打电话,为任何错误道歉。)
推荐阅读
- hive - 游侠权限 | 基于分区目录的 Hive 表访问
- ios - 实例成员“jpegData”不能用于“UIImage”类型
- aframe - 无法在 Oculus Go 上控制 VR 中的相机位置
- ruby - 比较 RUBY 中数组的键
- java - android setdate 格式“2018-11-14 11:01:02”
- python - 在 python 3.7 中包装生成器函数的多个装饰器 - 所有可能的硬币组合问题
- jenkins - 詹金斯构建失败;不理解詹金斯日志
- javascript - 开玩笑地和 sinon 打交道
- javascript - 为什么我的服务人员只缓存访问过的页面?
- docker - 使用 vscode 在 docker 容器中打开一个文件