为什么析构函数 运行 进入未分配的内存?

Why does destructor run into unallocated memory?

我有一个单链循环链表,正在编写一个析构函数来删除所有节点。析构函数首先将头部与其余部分切断,以防止无限循环,然后循环遍历列表并删除所有节点,最终,循环回到头部并将其删除。在程序中,我检查以确保指向节点的指针不为 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;
        }
    }

这与切断无关,您在删除元素的同时遍历列表的代码在非循环列表中同样有问题。您将指针前进 然后 删除它指向的内容(下一项)。

您需要删除 current 项(但是,当然,您还需要在此之前提取其 next 字段,因为一旦删除,所有内容变为未定义),类似于:

while (cur != nullptr) {
    node<T> *toDelete = cur;
    cur = cur->next;
    delete toDelete;
}

就您需要的完整解决方案而言,算法应该是:

def delCircList(head):
    # Ignore empty list.

    if head == null:
        return

    # Special for one-element list.

    if head.next == head:
        free head
        return

    # Sever link and set start point.

    curr = head.next
    head.next = null

    # Use normal deletion algorithm.

    while curr != null:
        toDelete = curr
        curr = curr.next
        free toDelete