尝试从单向链表C++中删除单个节点时出现读取访问冲突

Read access violation when attempting to delete a single node from a singly linked list C++

本文关键字:节点 单个 访问冲突 读取 删除 C++ 链表      更新时间:2023-10-16

我正在尝试从单向链表中删除一些节点。但是,Visual Studio 告诉我,我的函数中存在读取访问冲突。我发现这是一条特定的线。我已经检查以确保在尝试写入它们之前我没有删除任何节点(我很有信心,尽管我可能是错的。函数如下:

template <class dataType>
bool UnOrderedList<dataType>::remove(int remove) {
Node<dataType>* current = head;
Node<dataType>* copy = head;
Node<dataType>* trail = nullptr;
if (current == nullptr) {
return false;
}
if (head->data == remove) {
Node<dataType>* temp = head;
head = head->next;
delete temp;
return true;
}
while (current != nullptr) {
trail = current;
if (current->data == remove) { // error occurs on this line
Node<dataType>* temp2 = current;
current = trail->next;
delete temp2;
return true;
}
current = current->next;
}
return false;
}

我已经评论了发生错误的行。 Visual Studio说:"抛出异常:读取访问冲突。 电流0xDDDDDDDD。

我做错了什么吗?我很想知道将来如何避免这样做。我有兴趣了解有关指针及其工作原理的更多信息。 感谢您的任何帮助!

删除节点时,不会更新前一个节点的next指针。 下次通过循环时,您将访问此悬空指针并读取已释放的内存(Visual C++已将其设置为 0xDDDDDDDD(。

在删除当前节点之前,您需要将上一个节点的next指针更新为当前节点的next指针,以便跳过要删除的节点。

正如 JaMiT 所提到的,如果没有能够重现,就很难进行调试。请注意一些建议

  1. 你从不使用copy.

  2. 以下部分中的行为

while (current != nullptr) {
trail = current;
if (current->data == remove) { // error occurs on this line
Node<dataType>* temp2 = current;
current = trail->next;
delete temp2;
return true;
}
current = current->next;
}

看起来确实像你想做的事情。当您第一次进入循环时,trailcurrent是一回事(因为您将current分配给trail(。如果current节点不是要删除的节点,则current = current->next;。假设这不是nullptr,你循环回来,trail再次设置为current。您可能希望将trail设置为旧current(以便trail遵循current,顾名思义(。

while (current != nullptr) {
if (current->data == remove) {
Node<dataType>* temp2 = current;//save pointer to the node to delete later
trail->next = current->next;//skip this node - deleting it from the chain
delete temp2;//delete it
return true;
}
trail = current; //let trail follow current
current = current->next;
}
  1. 为什么UnOrderedList<dataType>remove需要int而不是dataType