尝试从单向链表C++中删除单个节点时出现读取访问冲突
Read access violation when attempting to delete a single node from a singly linked list C++
我正在尝试从单向链表中删除一些节点。但是,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 所提到的,如果没有能够重现,就很难进行调试。请注意一些建议
-
你从不使用
copy
. -
以下部分中的行为
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;
}
看起来确实像你想做的事情。当您第一次进入循环时,trail
和current
是一回事(因为您将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;
}
- 为什么
UnOrderedList<dataType>
的remove
需要int
而不是dataType
?
相关文章:
- 反向给定链表中的K节点
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Boost Graph Library,修复节点大小
- C++A*算法并不总是在路径中具有目标节点
- 从unordered_map中删除单个节点
- 如何在单个链表中交换两个节点的位置,只修改指针
- 尝试从单向链表C++中删除单个节点时出现读取访问冲突
- 在单个 Docker 容器中开发 ROS 节点?
- 单个链表,节点插入最低到最高节点值的问题
- C++ 删除单个链表中的节点
- 在单个链接列表中间删除一个节点,仅给定对该节点的访问
- 删除单个链接列表中的m节点
- 单个链表中的 C++ 插入节点
- 在只给定单个链接列表中间的节点的情况下删除该节点.C++
- 使用递归在单个链表中查找第n到最后一个节点
- 获取单个非循环链表中指针后面节点的值
- 将单个值解析为带有容器的ast节点
- 如何在单遍历中找到单个链表的中间节点(如果链表的长度未给定)
- 数据结构-在c++中,图中单个节点的许多边
- 从双链表类打印单个节点