简体   繁体   English

C ++二叉树递归析构函数问题

[英]C++ Binary Tree recursive destructor issue

I made a binary tree class which holds: int value, BinaryTree* left , BinaryTree* right . 我制作了一个二叉树类,其中包含: int值, BinaryTree* left BinaryTree* right

class BinaryTree {
private:
     int value;
     BinaryTree* left;
     BinaryTree* right;
     bool isVisited;
public:
     BinaryTree();
     BinaryTree createComplete(int n);
     ~BinaryTree();
}

My destructor is : 我的析构函数是:

BinaryTree::~BinaryTree() {
delete left;
delete right;   
}

When running in clion it works perfectly, but in my terminal I get a segfault (core dumped). 当在clion中运行时,它可以完美运行,但是在我的终端中,我遇到了段错误(核心被丢弃)。 Everywhere I looked people claimed that this should be the destructor. 我到处看的人都声称这应该是破坏者。 Any elaboration would help! 任何详细说明都会有所帮助!

I am not a stackoverflow expert , I updated my ~BinaryTree function to still gets a segfault : 我不是stackoverflow专家,我将〜BinaryTree函数更新为仍然存在segfault:

BinaryTree::~BinaryTree() {
if (right != NULL) {
   delete right;
}
if (left != NULL) {
   delete left;
}

} }

First of all your current implementation is not that of a complete tree. 首先,您当前的实现不是完整的树。 It is a node, thus I suggest renaming it to BinaryTreeNode and using it to construct a new class BinaryTree, that keeps track of the root and allows you to recursively deallocate the tree. 它是一个节点,因此我建议将其重命名为BinaryTreeNode并使用它来构造一个新的类BinaryTree,该类可以跟踪根并允许您递归地重新分配树。

Having said that your destructor most likely segfaults because you are blindly attempting to delete a pointer. 话虽如此,您的析构函数很可能发生段错误,因为您盲目地尝试删除指针。

First make sure you initialize left and right to nullptr. 首先,请确保您初始化为nullptr左右。 Then you do if(left != nullptr) { delete left } 然后,执行if(left != nullptr) { delete left }

Without seeing your constructor, I assume you don't initialize your node's children to NULL. 没有看到您的构造函数,我假设您没有将节点的子代初始化为NULL。 That might mean that the uninitialized nodes left and right at the bottom leaves have a random value in them. 这可能意味着底部叶子leftright的未初始化节点中具有随机值。 When the destructor runs, it will try to free the memory that the random garbage in the nodes point to. 当析构函数运行时,它将尝试释放节点中随机垃圾指向的内存。

Try initializing your child nodes to NULL when ctoring nodes, then making a check for it like monoceres suggested. 插入节点时,尝试将子节点初始化为NULL ,然后像建议的单片一样检查它。 It will also be good to set the pointer to NULL after delete to avoid situation of erronous double delete delete后将指针设置为NULL也将是很好的,以避免出现错误的双重delete

因此,在调试之后,我注意到每个正确的孩子都失去了它的节点,这在进行预遍历时是可以的,但是在删除它会引起问题时,感谢大家的帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM