代码运行完美,但在 运行 后以分段错误结束
Code runs perfectly but ends with a segmentation fault after running
我确定问题出在用于从链表中删除节点的删除函数,但我不明白为什么。
void LinkedList::remove(string license){
moveToHead();
while(currentPtr != NULL){
if(getCurrent().get_licence() == license){
if(currentPtr == headPtr){
removeFromHead();
}else if(currentPtr == tailPtr){
removeFromTail();
}else{
currentPtr->getNext()->setPrev(currentPtr->getPrev());
currentPtr->getPrev()->setNext(currentPtr->getNext());
delete currentPtr;
currentPtr = headPtr;
}
}
forward();
listLength--;
}
moveToHead();
}
moveToHead()
将我当前的指针移至头部,forward()
将其移至列表中的下一项。
代码运行没有问题,但我在完成 运行 后得到 segmentation fault (core dumped)
,而不是在使用 remove()
时崩溃
使用
g++ -fsanitize=address main.cpp
或相关变体来编译您的代码,然后 运行 它。这将告诉您如何滥用内存导致段错误。
单看逻辑,即使if(getCurrent().get_licence() == license){
为真,你也在调用forward();
和listLength--;
?如果找到并删除了正确的 license
,你不应该 return 吗?
我确定问题出在用于从链表中删除节点的删除函数,但我不明白为什么。
void LinkedList::remove(string license){
moveToHead();
while(currentPtr != NULL){
if(getCurrent().get_licence() == license){
if(currentPtr == headPtr){
removeFromHead();
}else if(currentPtr == tailPtr){
removeFromTail();
}else{
currentPtr->getNext()->setPrev(currentPtr->getPrev());
currentPtr->getPrev()->setNext(currentPtr->getNext());
delete currentPtr;
currentPtr = headPtr;
}
}
forward();
listLength--;
}
moveToHead();
}
moveToHead()
将我当前的指针移至头部,forward()
将其移至列表中的下一项。
代码运行没有问题,但我在完成 运行 后得到 segmentation fault (core dumped)
,而不是在使用 remove()
时崩溃
使用
g++ -fsanitize=address main.cpp
或相关变体来编译您的代码,然后 运行 它。这将告诉您如何滥用内存导致段错误。
单看逻辑,即使if(getCurrent().get_licence() == license){
为真,你也在调用forward();
和listLength--;
?如果找到并删除了正确的 license
,你不应该 return 吗?