[英]Segfaulting on deletion of a node in a doubly linked list
所以似乎正在發生的事情是我的程序沒有識別節點何時設置為nullptr ...我不知道為什么會這樣。 每當我檢查if(node != nullptr)
它似乎都會通過並直接進入語句。 我說這個可能是錯的,但這就是我認為正在發生的事情......也許你可能得出一個不同的結論。 以下是您需要的所有代碼,如果您需要我發布更多信息以便找到問題,請告訴我。
謝謝你提前幫助。
void UseList::deleteNode(std::pair <unsigned, unsigned> data){
node *pre = nullptr, *del = nullptr;
// Check if its the head, if so then delete and update it
if(head->data == data){
del = head;
head = del->next;
delete del;
return;
}
pre = head;
del = head->next;
while(del != nullptr) { // <----- On the first execution, head is nullptr, so head->next should also be nullptr. This line should not be allowing the program to descend into the code.
if(del->data == data){ // <----- Seg fault occurs here.
pre->next = del->next;
if(del = tail)
tail = pre;
delete del;
break;
}
pre = del;
del = del->next;
}
}
注意:調用此刪除時,列表為EMPTY。 它應該認識到head-> next是一個nullptr而不是試圖將其數據與要刪除的數據進行比較。
50 while(del != nullptr) {
(gdb)
51 if(del->data == data){
(gdb)
std::operator==<unsigned int, unsigned int> (__x=..., __y=...)
at c:/mingw/lib/gcc/mingw32/4.8.1/include/c++/bits/stl_pair.h:215
215 { return __x.first == __y.first && __x.second == __y.second; }
(gdb)
Program received signal SIGSEGV, Segmentation fault.
0x00406352 in std::operator==<unsigned int, unsigned int> (__x=..., __y=...)
at c:/mingw/lib/gcc/mingw32/4.8.1/include/c++/bits/stl_pair.h:215
215 { return __x.first == __y.first && __x.second == __y.second; }
(gdb)
class node {
public:
std::pair <unsigned, unsigned> data;
node *next;
node *prev;
node(){
next = nullptr;
prev = nullptr;
}
~node(){
delete next;
}
};
UseList::UseList(){
head = tail = nullptr;
head->next = head->prev = nullptr;
tail->next = tail->prev = nullptr;
}
我認為這是由一個錯字造成的。
你寫了:
if(del = tail)
tail = pre;
你可能意味着:
if(del == tail)
tail = pre;
我看到的問題
這可能不是你的問題,但值得指出。 你有:
if(head->data == data){
如果列表為空,這將是一個問題,即head == nullptr
。
構造函數中的代碼不正確。 你有:
UseList::UseList(){ head = tail = nullptr; head->next = head->prev = nullptr; // Since head is nullptr, head->next and head->prev should // produce run time errors. tail->next = tail->prev = nullptr; // Same thing here also. }
deleteNode
的while
循環需要仔細檢查以確保您正在做正確的事情。
你有:
if(del->data == data){ pre->next = del->next; if(del = tail) tail = pre; delete del; break; }
假設您的列表中有25個項目,並且給定的數據是列表中的第5個項目。 那時, pre
指向第4個節點, del
指向第5個節點。 然后你執行:
pre->next = del->next; // This is good.
然后你執行:
if(del = tail)
該語句將del
指向列表的尾部 - 第25個節點。 表達式(del = tail)
計算結果為“true”。 所以,你執行:
tail = pre;
現在tail
指向列表中的第4個節點。
然后你執行:
delete del;
刪除列表的第25個節點。
現在,列表是一個奇怪的狀態。 tail
指向第4個節點。 第25個節點已被刪除,但第24個節點仍然指向它。
如果head
為nullptr
,則無法訪問head->next
。
所以這行錯誤:
del = head->next; // if head is nullptr
也許你可以在head
為nullptr
的情況下以不同的方式編寫它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.