简体   繁体   中英

segmentation fault inorder traversal

i keep getting segmentation fault (core dump) because of the following lines :

void inOrder(){
        if(this->isNull())
            return ;
        this->left->inOrder();
        cout<<this->key<<' ';
        this->right->inOrder();
}

for the same input sometimes this function displays what is supposed to but in most cases just segfault. im pretty sure its not because of isNull() function:

bool isNull(){
        return this->null;
    }

where null is a private bool initialized with true by pseudoconstructor the whole code could be seen here: http://pastebin.com/RiiwqY3K Thank you :).

Consider a case where there is a node (let it be the root node) which does not have a left child, so,

root->left = NULL

So, when you call this->left->inOrder() you are calling the function on a null pointer (dereferencing a null pointer), which is a segmentation fault!

So, you do not exactly need a isNull function to check, you just need to add if conditions before you call inOrder something like this ::

if(this->left != NULL)
    this->left->inOrder();

Similarly for right subtree. I am assuming that you are explicitly handling the case in which the root of the tree is NULL, inOrder is called on it from main , so you also put an if condition in the main (or anywhere) before calling this function.

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