简体   繁体   中英

insertion in a binary tree in C

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);
 }
 }
}

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;
}

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