【发布时间】: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