【发布时间】:2020-03-14 17:52:01
【问题描述】:
我很绝望,因为这段代码时常给我一个分段错误,我不知道为什么。实际上它只是应该添加一些链表注释,打印它们然后通过释放内存来清空列表。
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() 之前,一切正常。所以我强烈假设可以在这个函数中找到错误。只需发布其余代码,因为我是结构的新手,并且不能 100% 确定正确处理它们。你知道我做错了什么吗?...
【问题讨论】:
-
提示:
void list_print(IntList *start) { IntList *cur = start; ... }可以写成void list_print(IntList *cur) { ... } -
调用
list_free()后,start是一个悬空引用。因此,list_print()的以下调用具有未定义的行为。
标签: c memory-management linked-list segmentation-fault singly-linked-list