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

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:

  1. Unnecessary new + pointer overwrite
    You allocate a new Node with Node * root_ptr = new Node;, but immediately overwrite that pointer with root_ptr = &(t.nodes[root_index]);. This creates a memory leak (you lose track of the new'd Node) and makes root_ptr point to an element managed by the vector<Node> in your Tree class.
  2. Deleting memory you don't own
    The elements in vector<Node> are controlled by the vector itself—you didn't allocate them with new, so you can't safely delete them. 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 current Tree class 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 only delete nodes you explicitly allocated with new.
  • The SIGTRAP error in Dev-C++ is a classic sign your program tried to access invalid memory—this often happens when freeing memory that wasn't allocated with new, or accessing already-freed memory.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:43:04