I've seen this question asked before here, specifically
Generic binary tree node destructor issue and Binary Search Tree Destructor among other things
but so far the answers I got was to set the Node pointers to NULL in the constructor. Here is the code of my constructors and destructors for the Node and the Tree.
template <class Type>
class Node {
protected:
Type data;
public:
Node<Type>(Type data) { this->data = data; }
};
The Binary Tree Node inherits from the Node above (I know that it would be easier to not use inheritance and simply go with a BinaryTreeNode straight with data, but I chose to do it this way because I am practicing)
The BinaryTreeNode class:
template <class Type>
class BinaryTreeNode: public Node<Type> {
protected:
BinaryTreeNode<Type> *left;
BinaryTreeNode<Type> *right;
BinaryTreeNode<Type> *parent;
public:
BinaryTreeNode<Type>(Type data) : Node<Type>(data) {
this->left = NULL;
this->right = NULL;
this->parent = NULL;
}
~BinaryTreeNode<Type>() {
delete left;
delete right;
delete parent;
}
};
For the Tree:
template <class Type, template <class> class NodeType = BinaryTreeNode>
class BinaryTree {
protected:
int size;
NodeType<Type> *root;
public:
~BinaryTree<Type, NodeType>() {
delete root;
}
BinaryTree<Type, NodeType>() {
this->size = 0;
this->root = NULL;
}
};
Now in main, I do the following:
BinaryTree<int> *bt = new BinaryTree<int>();
bt->insert(100);
bt->insert(50);
bt->insert(101);
The above works, so far so good.
The insert method/function is where creation of NEW nodes are done. I then tried using each of the following (one by one) and they all result in a segfault (core dump):
delete bt->getRoot();
This resulted in segfault. I then tried
delete bt->getRoot()->getRight();
again segfault. So last I tried
delete bt;
still segfault
I was expecting to simply have memory leaks due to other nodes being unreachable (I am running it with valgrind) but to my surprise, valgrind crashed, and gcc and clang did not even print out any warnings even with -Wall. I need advise on how to do this correctly. Thanks in advance.