Reputation: 435
The below code is running but after taking the second number to insert into the tree, the program is crashing.Why is it so? user input 1 is for inserting and 0 is for exit Thanks in advance...
#include<stdio.h>
#include<stdlib.h>
typedef struct ll
{
int data;
struct ll *left;
struct ll *right;
}node;
void insert(node **root,int n)
{
if((*root)==NULL)
{
(*root)=(node*)malloc(sizeof(node));
(*root)->data=n;
}
else if(((*root)->data)<n)
{
insert(&(*root)->right,n);
}
else if(((*root)->data)>n)
{
insert(&(*root)->left,n);
}
}
main()
{
node *head=NULL;int choice,n;
while(1)
{
printf("Enter 1 to insert node\n 0 to exit\n");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("Enter number\n");
scanf("%d",&n);
insert(&head,n);break;
case 0:exit(0);
}
}
}
Upvotes: 0
Views: 118
Reputation: 42165
You don't initialise the left
or right
members when you allocate a new node
if((*root)==NULL)
{
(*root)=(node*)malloc(sizeof(node));
(*root)->data=n;
}
allocates a node
but leaves its left
and right
members pointing to unpredictable values. When you allocate a second node
, insert
will try to dereference one of these values. This results in undefined behaviour; sooner or later you'll get a crash after attempting to dereference an address that isn't readable by your code or is incorrectly aligned.
You can avoid this by initialising all members of a new node
:
if((*root)==NULL)
{
(*root)=malloc(sizeof(node));
(*root)->data=n;
(*root)->left=NULL;
(*root)->right=NULL;
}
Alternatively, you could allocate memory using calloc
, to initialise the new node
's members to 0
if((*root)==NULL)
{
(*root)=calloc(1, sizeof(node));
(*root)->data=n;
}
Upvotes: 2