在hackerlink平台的列表中插入节点时出现分段故障



我正在hackerlink平台上运行一个测试。我必须在列表的末尾插入给定的数据。
类表示。。。

class SinglyLinkedListNode {
public:
int data;
SinglyLinkedListNode *next;
SinglyLinkedListNode(int node_data) {
this->data = node_data;
this->next = nullptr;
}
};

这已经嵌入到代码编辑器中。我无法更改它。

这是显式贴花函数,此函数与任何类都不关联。

// function to insert node at the tail of the list. 
SinglyLinkedListNode * insertNodeAtTail(SinglyLinkedListNode * head, int data) {
SinglyLinkedListNode * nn = new SinglyLinkedListNode(data);
// node to traverse the list
SinglyLinkedListNode * temp = head;
if (!head)
{
head = nn;
return head;
} 
else
{
while (temp)
{
temp = temp - > next;
}
temp - > next = nn;
}
return head;
}

我遇到分段故障
错误(stderr(消息:

Reading symbols from Solution...done.
[New LWP 113196]
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Core was generated by `./Solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  insertNodeAtTail (data=302, head=<optimized out>) at Solution.cpp:70
70         temp->next=nn;
To enable execution of this file add
add-auto-load-safe-path /usr/local/lib64/libstdc++.so.6.0.25-gdb.py
line to your configuration file "//.gdbinit".
To completely disable this security protection add
set auto-load safe-path /
line to your configuration file "//.gdbinit".
For more information about this security protection see the
"Auto-loading safe path" section in the GDB manual.  E.g., run from the shell:
info "(gdb)Auto-loading safe path"

正如我所看到的,我没有取消引用任何未分配的内存。错误是什么?

这段代码离开链表的末尾,然后取消引用一个NULL指针:

while(temp){
temp=temp->next;
}
temp->next=nn;

你实际上是在等待temp变成nullptr,然后才使用它。这是有问题的。

你需要的是向前看:

while(temp->next) {
temp = temp->next;
}
temp->next = nn;

您应该始终首先使用调试器。在这段代码中,您正在观察一个指针,而不是它的下一个指针

while(temp->next) {
temp = temp->next;
}
temp->next = nn;

这是正确的代码。

最新更新