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

C++动态模板队列析构时触发double free or corruption (out)错误求助

Fixing the "double free or corruption (out)" Error in Your C++ Dynamic Template Queue

Let's break down the issues step by step, starting with the one directly causing your crash:

1. The Root Cause: Incorrectly Deleting a Stack-Allocated Object

In your main function, this line is the source of your immediate problem:

delete &rq1; // ❌ This is a critical mistake!

The variable rq1 is an automatic stack-allocated object—the compiler automatically handles its lifecycle. It will call the queue's destructor for you when main exits. Using delete on a stack object is undefined behavior, because delete only works with memory allocated via new on the heap. This is exactly what triggers the "double free or corruption" error.

Quick Fix: Just remove this line entirely. Your queue's destructor will run automatically when main finishes, cleaning up the queue properly.

2. Bonus Fix: Memory Leak in the enqueue Function

While not causing the current crash, your enqueue logic creates unnecessary memory leaks:

  • In main, you explicitly new five queueNode instances (q1 to q5).
  • But in enqueue, you ignore these passed-in pointers and new a brand new copy of each node instead.

This means the original q1-q5 nodes are never deleted, leaving orphaned memory. To fix this, modify enqueue to use the passed-in node directly (instead of making a copy):

template <class T>
void resrcQueue<T>::enqueue(queueNode<T>* t){
    t->next = NULL; // Ensure the new node's next pointer is null
    if(head){ // Queue isn't empty
        tail->next = t;
        tail = t;
    } else { // Queue is empty
        head = t;
        tail = t;
    }
}

This way, the nodes you create in main are properly added to the queue, and the destructor will delete them via dequeue when the queue goes out of scope.

3. Verify the Fix

After making these two changes:

  • Remove delete &rq1; from main
  • Update the enqueue function to use the passed-in node
  • Recompile and run your program

Your queue will print correctly, and the destructor will clean up all nodes without any memory errors.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:27:52