为什么释放内存会导致分段错误?

Gre*_*eta 5 c memory-management linked-list segmentation-fault singly-linked-list

我很绝望,因为这段代码有时会给我分段错误,我也不知道为什么。实际上,仅应添加一些链接的列表注释,将其打印出来,然后通过释放内存来清空列表。

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");

}
Run Code Online (Sandbox Code Playgroud)

在尝试实现list_free()之前,一切工作都很好。因此,我强烈认为可以在此函数中找到错误。也只发布其余的代码,因为我是结构的新手,不确定100%正确地处理它们。你知道我在做什么错吗?

Vla*_*cow 1

该函数list_free通过值获取其参数。因此该函数处理指向节点的原始指针的副本。结果,指向节点的原始指针start保持不变。

因此,调用函数后列表的输出list_free

list_free(start);
printf("Empty list:\n");
list_print(start);
Run Code Online (Sandbox Code Playgroud)

有未定义的行为。

该函数应该像函数一样通过引用接受指向节点的原始指针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");
}
Run Code Online (Sandbox Code Playgroud)

调用函数如下

list_free( &start );
Run Code Online (Sandbox Code Playgroud)

退出函数后,原始指针start将等于NULL。那就是列表确实会被释放。

这比列表的客户端显式地将指针设置为NULL自己要好。他可能会犯与您忘记将指针设置为 NULL 相同的错误。