【发布时间】:2020-07-18 00:02:26
【问题描述】:
我有一个单链循环链表,并且正在编写一个析构函数来删除所有节点。析构函数首先将头部与其余部分分离以防止无限循环,然后循环遍历列表并删除所有节点,最终,循环返回头部并将其删除。在程序中,我检查以确保指向节点的指针不为 NULL,我运行了调试器,它显示它在应该结束循环的点为 NULL,但循环继续并运行到未分配的内存中.这是我的代码:
node<T> *cur = head;
node<T> *nxt = head->next;
if (nxt) cur->next = nullptr;
cur = nxt;
// walk through the list and delete nodes
while (cur) {
cur = cur->next;
delete cur;
}
编辑:将代码更改为
node<T> *cur = head;
node<T> *nxt = head->next;
if (nxt) cur->next = nullptr;
cur = nxt;
// walk through the list and delete nodes
while (cur) {
nxt = cur->next;
delete cur;
cur = nxt;
}
编辑 2: 再次更改代码以处理边缘情况,同样的问题仍然存在。
if (head == NULL) return;
else if (head->next == head) delete head;
else {
node<T> *cur = head;
node<T> *nxt = head->next;
cur->next = nullptr;
cur = nxt;
while(cur) {
nxt = cur -> next;
delete cur;
cur = nxt;
}
}
【问题讨论】:
-
更仔细地遵循您的循环逻辑。
delete cur;-- 那么在那一行之后cur会发生什么?你已经摧毁了它。那么while(cur)会发生什么? -
啊,可能需要一个临时指针
-
问题与我的删除功能有关,该功能正在删除列表的头部。
标签: c++ linked-list destructor dynamic-memory-allocation