Reputation: 41
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);
}
Upvotes: 4
Views: 87
Reputation: 2207
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
Upvotes: 1
Reputation: 15954
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.
Upvotes: 1