C++ 二叉树实现 - 删除指针原因



我正在C++中研究一个非常基本的二叉树实现,但我目前遇到删除指向根节点的指针会使程序崩溃的问题。在 Dev-C++ 调试模式下,返回的错误是:"程序接收信号 SIGTRAP,跟踪/断点陷阱",但当我检查"信息断点"时,它说没有断点或观察点。我对此感到非常困惑,并且花了很多时间检查我是否正确使用并声明了所有指针,任何帮助将不胜感激!

#include <iostream>
#include <vector>
using namespace std;

class Node {
  public: 
    int key;
    Node * left_child = NULL;
    Node * right_child = NULL;  
};

class Tree {
  public:
      int num_nodes;
      vector<Node> nodes;
   int read() {
    cin >> num_nodes;   
    nodes.resize(num_nodes); 
    int input_key, input_left, input_right, root_node = 0;
    for (int i = 0; i < num_nodes; i++) {
      cin >> input_key >> input_left >> input_right;
      if(input_key >= nodes.size()) {
        nodes.resize(input_key+1);
      }
      if(i==0) {
        root_node = input_key;
      }

      nodes[input_key].key = input_key;
      if(input_left >= 0) {
        nodes[input_key].left_child = &nodes[input_left];   
      } 
      if(input_right >= 0) {
        nodes[input_key].right_child = &nodes[input_right]; 
      }
    }
    return root_node;
  }
};

int main() {
    Tree t;
    int root_index = 0;
    root_index = t.read();
    Node * root_ptr = new Node;
    root_ptr = &(t.nodes[root_index]);
    delete root_ptr; //when I take this line out, it works
}

示例输入(预期无输出(:

3
4 2 5
2 -1 -1
2 -1 -1

首先,这一行是无用的:

Node * root_ptr = new Node;

您立即将root_ptr重新分配给其他内容。 因此,该行除了分配内存外什么都不做。 然后,按如下方式分配root_ptr:

 &(t.nodes[root_index]);

您在堆栈上声明的变量 t。 你最终会得到一个指向矢量元素的指针,一个你从未自己分配过的元素。 如果您没有自己分配它,则无法将其删除。 向量的任何分配都将由向量处理,并且向量本身是堆栈分配的,因此您无法删除它。

这就是删除行崩溃的原因。

此外,您说它是一个简单的二叉树实现,但事实并非如此。 你有一个向量,你有一种奇怪的方法来分配树元素,所以你创建了某种混合数据结构。

最新更新