C++二叉树实现问题:删除根节点指针致程序崩溃
Why Deleting Your Root Node Pointer Causes a Crash (and How to Fix It)
Hey there, let's break down why your program is crashing when you try to delete the root pointer, and how to fix it quickly.
The Root Cause of the Crash
Your code has two critical issues that trigger the SIGTRAP error:
- Unnecessary
new+ pointer overwrite
You allocate a new Node withNode * root_ptr = new Node;, but immediately overwrite that pointer withroot_ptr = &(t.nodes[root_index]);. This creates a memory leak (you lose track of thenew'd Node) and makesroot_ptrpoint to an element managed by thevector<Node>in yourTreeclass. - Deleting memory you don't own
The elements invector<Node>are controlled by the vector itself—you didn't allocate them withnew, so you can't safelydeletethem. Trying to free this vector-managed memory leads to undefined behavior, which is exactly why your program crashes.
Fixed Code for main()
Here's the corrected main function, with clear explanations:
int main() { Tree t; int root_index = t.read(); // Directly point to the node stored in the vector—no need for new! Node * root_ptr = &(t.nodes[root_index]); // You can use root_ptr here to traverse or modify the tree, e.g.: // cout << "Root node key: " << root_ptr->key << endl; // DO NOT delete root_ptr! The vector automatically cleans up its elements when it goes out of scope }
Extra Context
- If you intended to build a binary tree with dynamically allocated nodes (using
new), your currentTreeclass design (storing all nodes in a vector) doesn't match that goal. For that approach, you'd need to adjust how you create and link nodes, ensuring you onlydeletenodes you explicitly allocated withnew. - The
SIGTRAPerror in Dev-C++ is a classic sign your program tried to access invalid memory—this often happens when freeing memory that wasn't allocated withnew, or accessing already-freed memory.
内容的提问来源于stack exchange,提问作者MrDinkleburg
相关产品推荐
相关产品推荐

