I am having a problem in my code. I have run and debugged it several times. It seems to work fine if I do not throw an exception in my getEntry function. But when I do throw an exception, my program has a segmentation fault after that. When I debug through the program, it seems that the nextNodePtr in the getEntryHelper is not 0x0. So it somehow gets changed after it throws the exception and I have no idea why.
My main:
#include <iostream>
#include "BinarySearchTree.h"
int main {
BinarySearchTree<std::string,std::string> myTree;
myTree.add("book");
myTree.add("encyclopedia");
myTree.add("automobile");
myTree.add("zebra");
myTree.getEntry(zebra);
myTree.getEntry(xylophone);
myTree.getEntry(tree); // Does not get to here
}
Here are my add an and getEntry methods (although it appears that my getEntry is the problem:
template<typename KeyType, typename ItemType>
void BinarySearchTree<KeyType,ItemType>::add(const ItemType& newEntry) {
if(rootPtr == NULL)
rootPtr = new BinaryNode<ItemType>(newEntry);
else {
addHelper(rootPtr,rootPtr,newEntry);
}
}
template<typename KeyType, typename ItemType>
ItemType BinarySearchTree<KeyType,ItemType>::getEntry(const KeyType& aKey) const
throw(NotFoundException) {
try {
BinaryNode<ItemType>* temp = getEntryHelper(rootPtr,aKey);
std::cout << temp->getItem() << "\n";
return temp->getItem();
}
catch(NotFoundException& nf) {
std::cout << nf.what();
}
}
template<typename KeyType, typename ItemType>
void BinarySearchTree<KeyType,ItemType>::addHelper(BinaryNode<ItemType>* prevNodePtr,
BinaryNode<ItemType>* nextNodePtr,
const ItemType& newEntry) {
if(nextNodePtr == NULL) { // Base Case
nextNodePtr = new BinaryNode<ItemType>(newEntry,NULL,NULL);
if(newEntry < prevNodePtr->getItem())
prevNodePtr->setLeftChildPtr(nextNodePtr);
else
prevNodePtr->setRightChildPtr(nextNodePtr);
return;
}
if(newEntry < nextNodePtr->getItem()) {
prevNodePtr = nextNodePtr;
nextNodePtr = nextNodePtr->getLeftChildPtr();
addHelper(prevNodePtr,nextNodePtr,newEntry);
}
else {
prevNodePtr = nextNodePtr;
nextNodePtr = nextNodePtr->getRightChildPtr();
addHelper(prevNodePtr,nextNodePtr,newEntry);
}
}
template<typename KeyType, typename ItemType>
BinaryNode<ItemType>* BinarySearchTree<KeyType,ItemType>::getEntryHelper(BinaryNode<ItemType>* nextNodePtr,const KeyType& aKey) const {
if(nextNodePtr == NULL) {
throw NotFoundException("does not exist in tree.\n");
}
else if(nextNodePtr->getItem() == aKey)
return nextNodePtr;
else if(aKey < nextNodePtr->getItem()) {
getEntryHelper(nextNodePtr->getLeftChildPtr(),aKey);
}
else {
getEntryHelper(nextNodePtr->getRightChildPtr(),aKey);
}
}
Output: automobile book encyclopedia zebra zebra Precondition Violated Exception: xylophone does not exist in tree. Segmentation fault (core dumped)