I'm stuck on figuring out why I'm getting this error. Here is the code snippet:
int main() {
node *root = NULL;
char item1[6];
int item2;
in.open("input.txt");
while(in >> item1) {
if(strcmp(item1, "delete") == 0) {
in >> item2;
cout << root->item << endl;
if(!deleteLeaf(root, item2)) { // if deleteLeaf did not find(false)
}
}
else {
item2 = atoi(item1);
Insert(root, item2);
cout << root->item << endl;
}
}
return 0;
}
What I'm noticing is that first cout << root->item << endl;
is considered a NULL pointer dereference error, but why isn't the second one? I've noticed that if I also change cout << root->item << endl;
to cout << root << endl;
, I get two different address locations. Here is the code for Insert():
void Insert(node *&leaf, int item) {
if(leaf == NULL) {
leaf = new node;
leaf->right = NULL;
leaf->left = NULL;
leaf->item = item;
}
else if(item < leaf->item) {
Insert(leaf->left, item);
}
else {
Insert(leaf->right, item);
}
}
This is the input file:
1
2
delete 3
4
5
6
For background, this code is supposed to read from an input file and creates a binary tree using a doubly linked list. If I read in the word "delete", I need to search the list and delete the item if it exists, if it doesn't then I need to create the node. What I can't understand is why is cout << root << endl giving me two different addresses?
If you need anymore info, I'll be glad to provide it.
EDIT: I first, I thought it was a NULL pointer dereference error that was causing my problem of getting two different address locations for node *root
, but it was actually that I set my array size to 6 and not 7 that caused an overflow to change the address location unexpectedly. Thanks for the help guys!
I'm still new to stackoverflow so I'm not sure how to mark this as solved...