简体   繁体   中英

I'm unsure as to why I'm getting a NULL pointer dereference error

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...

Since initially you have node *root = NULL; and do not have anything allocated for it, it will be null pointer dereferencing. Notice you are actually allowed to print root itself, and it should give you a valid memory address regardless.

I'm also unsure as to what you mean by the "second one". Clarify please.

Additionally, your item array has to be of size 7, not 6, because of the +1 for '\\0' terminating character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM