I am writing a program for a project at school that requires us to create a Binary Search Tree
based on data read from a file (in this case strings). The tree should allow for duplicates by incrementing an integer value when a duplicate string is entered.
The TreeNode is a struct as follows:
struct TreeNode {
string word;
int count;
TreeNode * left;
TreeNode * right;
};
The problem I am having is when I try to call the insert function the program crashes. I run the debugger and I get the following error:
Exception thrown at 0x00E2A87C in Proj12.2.exe: 0xC0000005: Access violation reading location 0x00000014.
What is causing this error? Here is the rest of the relevant code:
TreeNode * Root = new TreeNode;
Root->right = NULL;
void insert(TreeNode *& root, string item) { //insert function, called by Root->right,temp
if (root->word == item) {
root->count++;
return;
}
if (root == NULL && root->word != item) {
root = new TreeNode;
root->left = NULL;
root->right = NULL;
root->word = item;
root->count = 1;
return;
}
if (item < root->word) {
insert(root->left, item);
}
if (item > root->word) {
insert(root->right, item);
}
}
if(root == NULL) should be the first check you perform before trying to access any data members using the -> operator. condition: if(root->word == item) condition: if (root == NULL && root->word != item)
Your root is NULL and then you are trying to access root->word which is causing the crash. You are trying to access data member using an invalid pointer.
User contributions licensed under CC BY-SA 3.0