【问题标题】:C++ Binary Tree Implementation - Deleting Pointer CausesC++ 二叉树实现 - 删除指针原因
【发布时间】:2018-06-29 23:23:52
【问题描述】:

我正在用 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

【问题讨论】:

  • 您正在尝试删除指向其他已分配内存(nodes 向量)中间的指针。你最终会泄露你最初分配并分配给root_ptr的指针。

标签: c++ pointers error-handling tree


【解决方案1】:

首先,这条线没用:

Node * root_ptr = new Node;

您立即将 root_ptr 重新分配给其他对象。所以这条线除了分配内存什么都不做。然后按如下方式分配 root_ptr:

 &(t.nodes[root_index]);

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多