【问题标题】:Cannot find seg fault error in Singly Linked List Insert Method在单链表插入方法中找不到段错误错误
【发布时间】: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-&gt;next = newNode;newnode是一个无处可去的垃圾指针。
  • 您永远不会为newNode 赋值,因此当您将其作为指针访问时可能会导致段错误。

标签: c++ debugging insert segmentation-fault singly-linked-list


【解决方案1】:

这里的问题是如果你的头是NULL 那么你的声明curr-&gt;next 是无效的内存位置。这就是你遇到分段错误的原因。而只是做if(curr==NULL)。并将学生分配给curr

【讨论】:

    猜你喜欢
    • 2015-02-01
    • 2021-07-07
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多