需要帮助在此代码中跟踪分段错误

时间:2015-04-19 00:13:07

标签: c++

编译器说segmentation fault但是没有告诉我哪一行。根据我的理解,分段错误通常意味着尝试访问地址NULL的值,但我不知道它发生了什么。

#include <iostream>

template <typename T> class SinglyLinkedList 
{

   struct node 
   {  
       T val;
       node * next;
   };

   public: 
     SinglyLinkedList ();
     SinglyLinkedList (T *, size_t); 
     ~SinglyLinkedList ();
     void push_back (T);
     void print ();
   private:
     node * _root;


};


int main () 
{
   int myArray [] = { 1, 69, -23942, 11111 };
   SinglyLinkedList<int> myList(myArray, sizeof(myArray)/sizeof(int));
   myList.print();
   return 0;
}

template <typename T> SinglyLinkedList<T>::SinglyLinkedList ( )
{
   _root = NULL;
}

template <typename T> SinglyLinkedList<T>::SinglyLinkedList (T * arr, size_t n)
{
   /* Initialize a singly-linked list of objects of type T from an array of objects of type T */
   if (n > 0)
   {    
       node * lastNode = new node;
       lastNode->val = *arr;
       lastNode->next = NULL;
       for (T * pa(arr+1), * pb(arr+n); pa != pb; ++pa)
       {
          node * thisNode = new node;
          thisNode->val = *pa;
          thisNode->next = NULL;
          lastNode->next = thisNode;
          lastNode = thisNode;       
       }
       delete lastNode;
   } 
   else
   {
       _root = NULL;
   } 
}

template <typename T> SinglyLinkedList<T>::~SinglyLinkedList ( )
{
   node * thisNode = _root; 
   while (thisNode != NULL)
   {
      node * temp = thisNode; 
      thisNode = thisNode->next;
      delete temp;
   }
}

template <typename T> void SinglyLinkedList<T>::print ( )
{
   if (_root == NULL) return; 
   for (node * thisNode = _root; thisNode != NULL; thisNode = thisNode->next)
   {
       std::cout << thisNode->val << "->";
   }
   std::cout << "NULL";
}

1 个答案:

答案 0 :(得分:3)

你的构造函数错了。

如果n> 0(在这种情况下)你做了很多指向指针(这不符合你的想法),但是没有为_root赋值。然后在print()中取消引用_root,它不指向有效对象;你很幸运,你得到的是一个段错误。