Search code examples
ccharbinary-search-treeinsertion

C binary search tree insertion by char element


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",&current->price);
        printf("\nAmount =");
        scanf("%d",&current->amount);
        printf("\nRelease date =");
        scanf("%d.%d.%d",&current->date_rel.dd,&current->date_rel.mm,&current->date_rel.yyyy);
        printf("\nExpiration date =");
        scanf("%d.%d.%d",&current->date_exp.dd,&current->date_exp.mm,&current->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;
}

Solution

  • 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.