I have to create a binary search tree by inserting in every node data about pharmaceutical drug . The nodes are sorted by a char NAME .I've got an error , a segmentation fault error at strcmp(name,(*parent)->name) < 0
.Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct date
{
int dd,mm,yyyy;
};
typedef struct node
{
char name[50];
float price;
int amount;
struct date date_rel;
struct date date_exp;
struct node *left , *right;
} node;
node *insert_node(node **parent,char name[])
{
node *current = NULL;
if(*parent == NULL)
{
current = (node *) malloc(sizeof(node));
strcpy(current->name,name);
printf("\nPrice =");
scanf("%f",¤t->price);
printf("\nAmount =");
scanf("%d",¤t->amount);
printf("\nRelease date =");
scanf("%d.%d.%d",¤t->date_rel.dd,¤t->date_rel.mm,¤t->date_rel.yyyy);
printf("\nExpiration date =");
scanf("%d.%d.%d",¤t->date_exp.dd,¤t->date_exp.mm,¤t->date_exp.yyyy);
*parent = current;
}
else
{
if(strcmp(name,(*parent)->name) < 0)
{
(*parent)->left = insert_node(&(*parent)->left,name);
}
else
{
(*parent)->right = insert_node(&(*parent)->right,name);
}
}
return *parent;
}
int main()
{
node *root = NULL;
char name[50] ;
int total_prod;
printf("The total number of medicines is:");
scanf("%d",&total_prod);
while(total_prod != 0)
{
printf("Name =");
scanf("%s",name);
insert_node(&root,name);
total_prod--;
}
return 0;
}
Most likely it's because you don't initialize the left
and right
pointers when *parent
is NULL
. As they are uninitialized they will have an indeterminate value, and in reality it will be seemingly random, and most likely not equal to NULL
which leads you to use them as valid pointers and you will have undefined behavior and get the crash.
Before the *parent = current
assignment you need to initialize the left
and right
pointers of current
to NULL
.