4

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);
}
philant
  • 34,748
  • 11
  • 69
  • 112
an111
  • 41
  • 1
  • Hello, welcome to StackOverflow. Please add the declaration of your node type. Are you sure the root value is modified in your main() function ? – philant Dec 18 '15 at 09:39
  • Why are you returning root? – BlueMoon93 Dec 18 '15 at 09:46
  • 1
    @BlueMoon93: Because this is how it gets modified? – undur_gongor Dec 18 '15 at 09:46
  • @undur_gongor: then should he not have "root->left=insert(root->left, value);"? I'm confused – BlueMoon93 Dec 18 '15 at 09:49
  • @BlueMoon93: In some cases, the root node has to be modified. You can do this by passing a pointer to the root pointer or by returning the (possibly modified) root. an111 used the second approach. Currently, the root node is only modified when the tree is empty. Later it might need modification due to re-balancing. – undur_gongor Dec 18 '15 at 09:51

2 Answers2

1

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.

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
1

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

  • as @undur_gongor has pointed out, you're not including stdlib.hand 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

Community
  • 1
  • 1
grasbueschel
  • 879
  • 2
  • 8
  • 24