编译器说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";
}
你的构造函数是错误的。
如果 n>0(如本例所示),则执行大量指针指向(它不会执行您认为的功能),但不为_root
分配任何值。然后在print()
中取消引用_root
,它不指向有效对象;你很幸运,你得到的只是一个赛格错误。