You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

循环双向链表clearList函数报错求助:无法正确释放节点

循环双向链表内存释放问题

我正在开发一个项目,使用包含quantity、price两个整数和itemName字符串的循环双向链表,节点结构体定义如下:

struct node {
    int quantity, price;
    string itemName;
    node * next;
    node * prev;
    node (int x = 0, int y = 0, string str = "", node * p = NULL, node * r = NULL): quantity(x), price(y), itemName(str), next(p), prev(r){}
};

目前addSorted、打印列表等功能运行正常,但clearList函数存在问题——在addItem函数中用new创建的节点无法被释放,当前clearList函数代码如下:

void clear(node * head){
    if (head == NULL) {
        cout << "List is empty." << endl;
    }
    else {
        node * ptr = head->next;
        while(ptr != head)
        {
            ptr = head;
            head = head->next;
            delete ptr;
        }
    }
}

出现的报错信息如下:

main(21281,0x100098600) malloc: *** error for object 0x103033080: pointer being freed was not allocated
main(21281,0x100098600) malloc: *** set a breakpoint in malloc_error_break to debug


问题原因

  1. 节点遗漏释放:当前逻辑只释放了除头节点外的其他节点,循环结束后原头节点始终未被释放。如果链表只有一个节点,ptr = head->next等于head,循环直接不执行,头节点完全没被处理;后续若外部代码误操作这个未释放的头指针,就会触发“释放未分配指针”的错误。
  2. 指针管理混乱:函数内修改head指针但未同步到外部,外部会继续持有野指针,后续任何对该指针的操作都可能引发内存错误。

解决方法

修改clear函数,确保所有节点被完整释放,同时避免野指针问题:

void clear(node* &head) {
    if (head == NULL) {
        cout << "List is empty." << endl;
        return;
    }

    node* current = head;
    do {
        node* nextNode = current->next;
        delete current;
        current = nextNode;
    } while (current != head);

    // 释放后将头指针置空,避免外部持有野指针
    head = NULL;
}

关键修改说明

  • 引用传递头指针:用node* &head替代node* head,函数内修改head为NULL的操作会同步到外部,彻底杜绝野指针。
  • do-while循环遍历:确保链表只有一个节点时,也能进入循环完成释放。
  • 先存下一个节点再删除:避免删除当前节点后无法访问后续节点的指针。
  • 清空头指针:防止外部代码误操作已释放的内存空间。

另外要确认:所有链表节点都是通过new动态分配的,不能将栈上的节点加入链表——如果存在栈节点,delete时也会触发类似错误,这一点需要在addItem等创建节点的函数中严格保证。

内容的提问来源于stack exchange,提问作者Oprasis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 09:33:21