【问题标题】:Segmentation fault linked lists分段错误链表
【发布时间】:2014-05-23 13:08:35
【问题描述】:

我在尝试创建一个简单的链表时不断遇到分段错误。问题似乎发生在 print_list 函数内部。我已经尝试解决这个问题大约一个小时,但它仍然无法正常工作。我真的感谢您的帮助。这是代码:

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

struct node{
   double value;
   struct node *next;
   };
 struct node* getnode()
   {  
      struct node* create;
      create=(struct node*)malloc(sizeof(struct node));
      create->next=NULL;
      return create;
   }     


 void insert_at_beg(struct node*first,double x)
  {                                                     
      struct node*temp=getnode();
      if(!first)
      {
         temp->value=x;
         first=temp;
      }
      else
      { 
          temp->value=x;
          temp->next=first;
          first=temp;
      }
  }   
 void print_list(struct node*first)
  {    
       struct node*temp;
       temp=first;

       if(temp==NULL)
        { printf("The list is empty!\n");
          return;
          }

      while(temp!=NULL)
            if(temp->next ==NULL) // this is where i get the segmentation fault
            {  printf("%lf ",temp->value);
               break;
            }
            else
             { 
                printf("%lf ",temp->value);
                temp=temp->next;
             }

       printf("\n");
   }


   int main()
   {
       struct node *first;
       insert_at_beg(first,10.2);
       insert_at_beg(first,17.8);
       print_list(first);

       system("PAUSE");
   }

【问题讨论】:

标签: c list linked-list segmentation-fault


【解决方案1】:

让它返回列表的新头:

void insert_at_beg(struct node *first, double x)
{                                                     
      struct node *temp = getnode();
      temp->value = x;
      temp->next = first;
      return temp;
}

也简单一点。 :)

然后在main(),做:

   struct node *first = insert_at_beg(NULL, 10.2);
   first = insert_at_beg(first, 17.8);

【讨论】:

    【解决方案2】:

    您可以使用 gdb - [GNU 调试器]。它应该可以帮助您找出分段错误的确切位置。您可以在此link 中找到更多信息

    【讨论】:

      【解决方案3】:

      您的 temp->next 调用中的地址无效。 C 不会默认初始化你需要将第一个值设置为 NULL 的变量

      struct node* first = NULL;
      

      【讨论】:

        猜你喜欢
        • 2018-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-06
        相关资源
        最近更新 更多