【发布时间】:2016-02-05 20:07:12
【问题描述】:
我正在尝试实现一个使用单链表的 SortedList 类。该列表按可以从学生类中检索到的学生 ID 号排序(并且在此方法中将学生对象作为参数传入)。调用我的插入方法时,我收到一个段错误错误。我已经尝试使用 linux 终端和一些打印行进行调试,但我无法确定错误的确切位置。
使用当前代码,打印的最后一个 cout
// insterts a student into the list in a sorted manner according to their ID
bool SortedList::insert(学生 *s){
// need to have in order of smallest student ID to Largest.
struct Listnode *newNode, *curr;
curr = head;
cout << "Created list nodes" << endl;
// first check if the list is empty, if so add to head's next
if(curr->next == NULL){
//newNode->student = s; // give the new node the parameter student
head->next = newNode; // assign the head to the (now) first node in list
cout << "Added first node in list empty if" << endl;
return true; // return indicating that the student was added
}
if(find(s->getID()) != NULL){ // if a student is found, return false
return false;
}
cout << "Finished find student check, wasn't found" << endl;
int counter = 1;
while(curr->student->getID() > s->getID() && curr->next != NULL){ // iterate through list to find proper spot in sorted list by checkin ID
cout << "Executed loop " << counter << " times" << endl;
counter++;
curr = curr->next; // advance curr
}
cout << "Finished while loop" << endl;
newNode->student = s; // store the student in the node
newNode->next = curr-> next; // set the new nodes next value in the chain
curr->next = newNode; // link the node before the new node, to the new node
return true; // return true since the new node was added
}
【问题讨论】:
-
head的初始值是多少? -
以上不是例子,可以直接用来复现错误;投票结束。
-
我猜你的情况是
curr==head==nullptr -
右上方
head->next = newNode;,newnode是一个无处可去的垃圾指针。 -
您永远不会为
newNode赋值,因此当您将其作为指针访问时可能会导致段错误。
标签: c++ debugging insert segmentation-fault singly-linked-list