【发布时间】:2021-12-31 09:59:30
【问题描述】:
while(n >= 0);
node * point = malloc(sizeof(node));
point = create(number, n);
//show(point);
//free memory
while(point != NULL)
{
node *tmp = point->next;
free(point);
point = tmp;
}
}
node * create(int data[], int len)
{
node * list_head;
node * list;
for (int i = 0; i < len; i++)
{
if(i == 0)
{
list_head = malloc(sizeof(node));
list = malloc(sizeof(node));
list_head->value = data[0];
list_head->next = list;
}
else
{
list->value = data[i];
list->next = malloc(sizeof(node));
list->next = NULL;
}
}
return list_head;
}
此代码返回的错误是:- free(): invalid pointer 中止 |为什么我的代码没有释放我分配的内存。是不是因为我在一些不同的功能中分配了它?
【问题讨论】:
-
仅供参考,C 指针不是 Java 或 C# 引用。这段代码像疯了一样泄漏内存。
-
while(n >= 0);看起来像无限循环或无操作 -
这两行有
list->next = malloc(sizeof(node)); list->next = NULL;表示错误 -
除其他错误外,分配
list时,并没有对其进行初始化。所以最后的 ->next 总是不确定的。
标签: c pointers linked-list