简体   繁体   中英

Binary Search Tree Insertion throws segmentation Fault

Can somebody please explain what is wrong with the below code for binary search insertion?It gives segmentation fault when I try to insert 2nd element.

node * insert(node * root, int value)
{
    if(root == NULL){
        node *newnode = (node *)malloc(sizeof(node));
        newnode->data = value;
        newnode->left = NULL;
        newnode->right = NULL;
        root = newnode;
    }
    else{
        if(root->data > value)
            insert(root->left, value);

        if(root->data < value)
            insert(root->right, value);
    }
   return root;
}

int main(){
    node* root = NULL;
    root = insert(root, 5);
    root = insert(root, 10);
}

You have to include stdlib.h .

Otherwise, the compiler doesn't know the prototype of malloc and assumes it returns an int rather than a pointer. If your ABI treats pointers and integers differently, this leads to problems.

The corresponding warning is hidden by the cast.

As I see it, there're two possibilities for why this might crash:

  • as @undur_gongor has pointed out, you're not including stdlib.h and run on an architecture with different sizes for integers and pointers. This would perfectly match a reason for why you shouldn't cast the result of malloc

  • you're out of memory. Since you don't check the result of malloc it may have failed and returned NULL

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