【发布时间】:2018-06-01 23:09:00
【问题描述】:
晚上好。 尝试销毁我的 BST 时出现访问冲突异常错误。 之前有过关于这个的帖子,我复制了他们接受的答案的回复,但仍然没有得到预期的结果。 所以我有这个二叉搜索树实现。一切正常,直到我的代码从我的 int main() 函数到达“return 0”。
我会为你留下一些代码。
PQBST::~PQBST()
{
destroy();
}
inline void PQBST::destroy()
{
if (root)
destroy(root);
}
void PQBST::destroy(Node* node)
{
if (node->left) // this is where it gives me and access violation exception 0xDDDDDDDD
destroy(node->left);
if (node->right)
destroy(node->right);
delete node;
}
我知道当你尝试删除已经被释放的东西时会抛出这种错误,但我不明白为什么当我在我的应用程序(当我完成它时)。 我评论了我手动销毁我的 BST 的部分,在达到“返回 0”后,它又给了我
Unhandled exception thrown: read access violation.
node was 0xFF12C6AB
所以它不是 0xDDDDDDDD 但仍然是一个错误。 :|
我的节点如下所示:
struct Node
{
Human info;
Node * left;
Node * right;
Node() {};
Node(Human value)
: info(value), left(NULL), right(NULL)
{
}
};
我的 BST 类只有 Node* root 。 我希望我给了你足够的信息。 谢谢。
编辑:我的节点现在看起来像这样:
struct Node
{
Human info;
Node * left;
Node * right;
Node() { left = NULL, right = NULL; }
Node(Human value): info(value), left(NULL), right(NULL){}
Node(Human value, Node* left, Node* right) : info(value), left(left), right(right) {}
Node& operator=(const Node& n)
{
info = n.info;
left = n.left;
right = n.right;
return *this;
}
Human getInfo() const { return info; }
Node* getLeft() { return left; }
Node* getRight() { return right; }
~Node() { };
};
我的 PQBST:
class PQBST
{
private:
Node * root;
int m; //spaceship size - given by the user
public:
PQBST() { root = NULL; }
PQBST(int m) : root(NULL), m(m) {}
PQBST(Node* root, int m);
~PQBST();
PQBST::PQBST(Node * root, int m)
{
this->root = root;
this->m = m;
}
【问题讨论】:
-
在取消引用和访问成员之前,
void PQBST::destroy(Node* node)中的任何内容都不会检查非NULL。 -
Node() {};使left和right未初始化。厄运的可能性很大。 -
根据the big list of magic numbers at Wikipedia,0xDDDDDDDD 是已经被释放的内存。确保您已正确实施the Rule of Three
-
打开的错误可能性太多。投票结束。建议使用minimal reproducible example 缩小问题范围。
-
好的,我会试着查一下你说的。谢谢! *抱歉没有一个足够简单的例子,我不知道还要添加什么。
标签: c++ binary-search-tree access-violation