Reputation: 2172
I am working with Trees, for practice purpose. Precisely Binary Search Trees currently. I have a general Tree
class which I use to solve the BST problems.
So, I come across a problem tp convert the given tree (BST) into a Doubly linked list.
I am able to successfully convert the tree into a DLL. But, the problem is when I call the destructor
.
Since, I am allocating memory to the nodes of my Tree, I also wish to free the memory.
This is the destructor of the Tree
class ::
~Tree() {
delete root;
root = NULL;
}
And this is the destructor of the Node
class::
~Node() {
delete left;
delete right;
left = NULL;
right = NULL;
}
So, the program crashes at the end! To my understanding since the destructors that I have written kindof recursively delete all the nodes of the tree, and when the Tree is converted to a DLL, the left and right pointers indeed point to each other, so, during the call to the destructor, the destructor tries to delete the node which has already been deleted and that pointer has not been set to NULL. How do I overcome this? Since destructor overloading is not permitted.
Is there any way I could prevent this runtime error?? This is the code :: http://ideone.com/SDkXY9 (Ideone doesn't print the output, I don't know why!)
Upvotes: 0
Views: 846
Reputation: 764
The problem here is that you are trying to delete neighbours from whom the chained destruction is initiated. You will have to add a flag which you can check in the destructor for which neighbour is sane to delete.
~Node() {
_isDestructing = true;
if (!left->_isDestructing) delete left;
if (!right->_isDestructing) delete right;
left = NULL;
right = NULL;
}
Upvotes: 2