[英]Why does freeing the memory lead to segmentation fault?
我很绝望,因为这段代码不时给我一个分段错误,我不知道为什么。 实际上它只是应该添加一些链表注释,打印它们然后通过释放 memory 来清空列表。
struct int_list {
int value;
struct int_list *next;
};
typedef struct int_list IntList;
void list_print(IntList *start)
{
IntList *cur = start;
while(cur != NULL)
{
printf("%d\n", cur->value);
cur = cur->next;
}
}
void list_append(IntList **start, int newval)
{
IntList *newel = malloc(sizeof(IntList));
newel->value = newval;
newel->next = NULL;
if(*start == NULL)
{
*start = newel;
}
else
{
IntList *cur = *start;
while(cur->next != NULL)
{
cur = cur->next;
}
cur->next = newel;
}
}
void list_free(IntList *start)
{
IntList *prev = start; // prev = start
while (start != NULL) // if start != Null
{
start = start->next; // make start point to the next element
printf("Deleting %d\n", prev->value);
free(prev); // delete the previous element
prev = start; // make previous point to start again
}
printf("\n");
}
int main(int argc, char *argv[])
{
// fill the list
IntList *start = NULL;
list_append(&start, 42);
list_append(&start, 30);
list_append(&start, 16);
// print the list
printf("\nList 1\n");
list_print(start);
printf("\n");
// free the memory and print again
list_free(start);
printf("Empty list:\n");
list_print(start);
printf("\n");
}
在我尝试实现 list_free() 之前,一切正常。 所以我强烈假设错误可以在这个 function 中找到。 只需发布代码的 rest,因为我是结构新手,并且不能 100% 确定是否正确处理它们。 你知道我做错了什么吗?...
由于悬空指针,您有未定义的行为
list_free(start);
也就是说, start
仍然指向您尝试访问的已释放 memory 。
您需要在free
之后将start
设置为NULL
。
list_free(start);
start = NULL;
printf("Empty list:\n");
list_print(start);
function list_free
按值获取其参数。 因此 function 处理指向节点的原始指针的副本。 结果,指向节点start
的原始指针保持不变。
因此,在调用 function list_free 之后,列表的list_free
list_free(start);
printf("Empty list:\n");
list_print(start);
具有未定义的行为。
function 应该像 function list_append
那样通过引用接受指向节点的原始指针。
例如
void list_free( IntList **start )
{
while ( *start != NULL )
{
IntList *prev = *start; // prev = start
*start = ( *start )->next; // make start point to the next element
printf("Deleting %d\n", prev->value);
free(prev); // delete the previous element
}
printf("\n");
}
像这样调用 function
list_free( &start );
退出 function 后,原始指针start
将等于NULL
。 那就是列表确实会被释放。
这比列表的客户端自己显式设置指向NULL
的指针要好。 他可能会犯与您忘记将指针设置为 NULL 相同的错误。
指针仍然指向已释放的 memory 的 memory 位置,这也是分段错误的一个实例。 这是“未定义的行为”,并且可能导致任意不可预测的事情发生,因为指向位置的内容是未知的,运行时间不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.