Insert binary search Insert throws segmentation Fault

Can someone explain what is wrong with the code below to insert a binary search? It gives a segmentation error when I try to insert the second 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);
}
+4
source share
2 answers

You must enable stdlib.h.

Otherwise, the compiler does not know the prototype mallocand assumes that it returns intinstead of a pointer. If your ABI treats pointers and integers differently, this leads to problems.

The corresponding warning is hidden by the application.

+1
source

As I can see, there are two possibilities why this can happen:

  • @undur_gongor, stdlib.h . malloc.

  • . malloc, , NULL

+1

Source: https://habr.com/ru/post/1620709/


All Articles