打印链表时出现分段错误

Segmentation fault when printing the linked list

我一直在阅读链表的斯坦福教程。我使用了创建三个数字 (1,2,3) 列表的函数之一。该函数本身不会打印结果,所以我决定自己测试一下。但是,当我 运行 它时,它给我分段错误。

话虽如此,当我删除该函数并将代码复制到 main 中时,它起作用了。有人可以解释为什么 main 不适用于该功能吗?

这是给我分段错误的代码:

#include <stdio.h>
#include <stdlib.h>

      struct node {
         int            data;
         struct node*   next;
};

struct node* BuildOneTwoThree() 

{
   struct node* head = NULL;
   struct node* second = NULL;
   struct node* third = NULL;
   head = malloc(sizeof(struct node));
   second = malloc(sizeof(struct node));
   third = malloc(sizeof(struct node));

head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;

return head;

}


int main()

{
   struct node* head;
   struct node* second;
   struct node* third;
   struct node*   next;

   int data;

   BuildOneTwoThree();

   struct node* current = head;



while(current != NULL)
   {
      printf("%d ", current->data );

      current= current->next;

   }

}

这个有效:

#include <stdio.h>
#include <stdlib.h>

      struct node {
         int            data;
         struct node*   next;
};



int main()

{

   int data;

   struct node* head = NULL;
   struct node* second = NULL;
   struct node* third = NULL;
   head = malloc(sizeof(struct node));
   second = malloc(sizeof(struct node));
   third = malloc(sizeof(struct node));

head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;

   struct node* current = head;



while(current != NULL)
   {
      printf("%d ", current->data );

      current= current->next;

   }

}

在不起作用的版本中,您忽略了 BuildOneTwoThree 的 return 值,并从 main 分配了未初始化的局部变量 head(这是与 BuildOneTwoThree 范围内的同名局部变量不同)到变量 current.

因此打印代码应使用:

struct node* head = BuildOneTwoThree();
current = head;

相反,使用 BuildOneTwoThree() 中分配的 head 节点,并分配给 main 的头指针。