For some reason, after AddToBinarySearchTree
is called, an exception is thrown from the ~BinarySearchTreeNode<T>
destructor. I think this could be happening because the Node
itself is deleted before the tree is deleted - but I don't think this is the case.
Why would calling delete m_left;
throw the following exception?
Access violation reading location 0xFEEEFEF2
int _tmain(int argc, _TCHAR* argv[])
{
void AddToBinarySearchTree(BinarySearchTree<T> bst, T value) {
bst.Add(value);
}
void MyMethod() {
BinarySearchTree<int> bstStack;
bstStack.Add(5)
// the exception is thrown after this line of code executes
AddToBinarySearchTree(bstStack, 1000);
}
}
// BinarySearchTreeNode<T>
template <typename>
BinarySearchTreeNode {
public:
BinarySearchTreeNode<T>::~BinarySearchTreeNode() {
// executing the following line of code throws the exception
delete this->m_left;
this->m_left = NULL;
delete this->m_right;
this->m_right = NULL;
}
};
// BinarySearchTree<T>
template <typename T>
class BinarySearchTree {
BinarySearchTree<T>::~BinarySearchTree() {
delete m_head;
m_head = NULL;
}
void BinarySearchTree<T>::Add(T value) {
Add(new BinarySearchTreeNode<T>(value));
}
AddRecursive(BinarySearchTreeNode<T>* node, BinarySearchTreeNode<T>* parentNode) {
if (node->GetValue() < parentNode->GetValue()) {
if (!parentNode->GetLeft()) {
parentNode->SetLeft(node);
}
else {
this->AddRecursive(node, parentNode->GetLeft());
}
}
else if (node->GetValue() > parentNode->GetValue()) {
if (!parentNode->GetRight()){
parentNode->SetRight(node);
}
else {
this->AddRecursive(node, parentNode->GetRight());
}
}
}
};
Note: some class details have been omitted