【问题标题】:Segmentation fault in printing a linked list打印链表中的分段错误
【发布时间】:2013-12-22 15:38:51
【问题描述】:

这是一个简单的程序,它从用户那里获取 5 个元素并打印出来。但它在第 30 行显示分段错误。请帮助。这是我的代码。

#include<stdio.h>
#include<stdlib.h>
struct node
{
int num;
struct node * next;
};

main()
{
int i;
struct node *p,*temp,*r;
p=NULL;
temp=p;
temp=malloc(sizeof(struct node));
scanf("%d",&(temp->num));
temp->next=NULL;
for(i=0;i<4;i++)
{
    while(temp->next!=NULL)
    temp=temp->next;
    r=malloc(sizeof(struct node));
    scanf("%d",&(r->num));  
    r->next=NULL;
    temp->next=r;
}
temp=p;
for(i=0;i<5;i++)
{
    printf("%d\n",temp->num);
    temp=temp->next;
}

}

【问题讨论】:

    标签: c linked-list segmentation-fault


    【解决方案1】:

    这里

    temp=p;       // p is NULL!!
    for(i=0;i<5;i++)
    {
        printf("%d\n",temp->num);   // <-- BANG!
        temp=temp->next;
    }
    

    您将 temp 重新分配为 p,之前已声明为 NULL。因此,您正在取消引用 NULL 指针。查看您的代码,您可能甚至不需要p 仅在开始时将temp 初始化为NULL。

    【讨论】:

    • 实际上 p 是我的头指针,这样我就不会丢失列表的开头点..
    【解决方案2】:

    你的 main 函数的一个简单的改变就是这样,问题是 temp=p=NULL 然后在 printf("%d\n",temp->num); 中使 null 指向 num;

    所以你的主要应该是这样的

    main()
    {
    int i;
    struct node *p,*temp,*r;
    temp=malloc(sizeof(struct node));
    p=temp;
    scanf("%d",&(temp->num));
    temp->next=NULL;
    for(i=0;i<4;i++)
    {
        while(temp->next!=NULL)
        temp=temp->next;
        r=malloc(sizeof(struct node));
        scanf("%d",&(r->num));
        r->next=NULL;
        temp->next=r;
    }
    temp=p;
    for(i=0;i<5;i++)
    {
    printf("%d\n",temp->num);
    temp=temp->next;
    }
    
    }
    

    【讨论】:

      【解决方案3】:

      你有:

      struct node *p,*temp,*r;
      p=NULL;
      

      后续代码永远不会将p 设置为非空值。然后你使用:

      temp=p;
      for(i=0;i<5;i++)
      {
          printf("%d\n",temp->num);
          temp=temp->next;
      }
      

      所以你取消引用一个空指针。这会导致不愉快和崩溃。

      1. p 重命名为 roothead 以表明其作为列表开头的重要作用。
      2. 将指向列表第一个元素的指针分配给新重命名的变量。

      例如,而不是:

      temp=p;
      temp=malloc(sizeof(struct node));
      

      使用(不重命名):

      p = temp = malloc(sizeof(struct node));
      

      或:

      p = temp = malloc(sizeof(*p));
      

      此外,您应该错误检查malloc()scanf() 调用;两者都可能失败。

      【讨论】:

        猜你喜欢
        • 2015-12-28
        • 1970-01-01
        • 2015-05-18
        • 1970-01-01
        • 2013-01-01
        • 2017-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多