为什么我会出现分段错误?

时间:2016-03-03 00:54:12

标签: c++ linked-list segmentation-fault

以下代码是我整个程序的摘录。我定义的唯一内容是构造函数(head = 0),析构函数和一个函数,该函数用于创建一个包含20个值的链表。它们应该是随机的(我可以处理),但我需要先解决这个seg故障。帮助!

节点的结构类型是:

struct ListNode
{
    int value;
    ListNode *next;
};
ListNode *head;

代码:

void NumberList::buildSortedList(){
   ListNode *newNode;   
   int number = 1;    
   int count = 0;    
   head->value = number;    
   ListNode *p;   
   do{ 
      p = head;       
      while (p->next) { // traverse the list to the end to append new value 
         p = p->next;     
      newNode = new ListNode; 
      newNode->value = number; 
      newNode->next = NULL;       
      p->next = newNode;      
     }         
   }while (count < 19);   
   }

2 个答案:

答案 0 :(得分:0)

  while (p->next) { // traverse the list to the end to append new value 
     p = p->next;

  newNode = new ListNode; 
  newNode->value = number; 
  newNode->next = NULL; 

  p->next = newNode; 

 }

应该是

  while (p->next) { // traverse the list to the end to append new value 
     p = p->next;
  }

  newNode = new ListNode; 
  newNode->value = number; 
  newNode->next = NULL; 

  p->next = newNode; 

答案 1 :(得分:0)

如果head是全局变量,则将其初始化为NULL。取消引用NULL是非法的。

在解除引用之前,必须先指定一个指向有效缓冲区的指针。

void NumberList::buildSortedList(){

   ListNode *newNode;

   int number = 1; 

   int count = 0; 

   if (head == NULL) head = new ListNode; // add this line
   head->value = number; 

   ListNode *p; 

   do{ 
      p = head; 

      while (p->next) { // traverse the list to the end to append new value 
         p = p->next;
      }  // move this in order not to break the list

      newNode = new ListNode; 
      newNode->value = number; 
      newNode->next = NULL; 

      p->next = newNode; 


   }while (count++ < 19); // add ++ to avoid infinite loop

}