C++动态模板队列析构时触发double free or corruption (out)错误求助
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 explicitlynewfivequeueNodeinstances (q1toq5). - But in
enqueue, you ignore these passed-in pointers andnewa 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;frommain - Update the
enqueuefunction 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

