Search code examples
cmallocbinary-search-treedynamic-memory-allocation

Binary search tree insertion program is showing segmentation fault


The node insertion code is throwing segmentation fault. This code is throwing segmentation fault when i am trying to print the data stored in the root node.

Below is the implementation of the insertion program for the Binary Search Tree. This program is using recursion to insert a given node.

#include <stdio.h>
#include <stdlib.h>

struct node
{
  int data;
  struct node *left;
  struct node *right;
};

struct node *make (int);
struct node *insert (struct node *, int);

void
main ()
{
  struct node *root;
  root = NULL;

  insert (root, 2);
  insert (root, 3);
  insert (root, 4);
  insert (root, 5);
  insert (root, 6);
  insert (root, 7);
  printf ("%d", root->data);
}

struct node *
make (int x)
{
  struct node *temp;
  temp = (struct node *) malloc (sizeof (struct node *));
  temp->data = x;
  temp->left = NULL;
  temp->right = NULL;
  return temp;
}

struct node *
insert (struct node *root, int x)
{
  if (root == NULL)
  {
    root = make (x);
  }
  else
  {
    if (x <= root->data)
    {
      root->left = insert (root->left, x);
    }
    else if (x > root->data)
    {
      root->right = insert (root->right, x);
    }
  }
  return root;
}   

Solution

  • The problem is that you are not assigning the returned value of the function insert to the node root.

    Write

    root = insert(root,2);

    //...

    Another problem is that you are allocating memory incorrectly

    temp = (struct node *) malloc (sizeof (struct node *));
                                           ^^^^^^^^^^^^^
    

    There must be

    temp = (struct node *) malloc (sizeof (struct node ));
                                           ^^^^^^^^^^^^^
    

    Also within the function insert the inner if statement should look like

    if (x < root->data)
    {
        root->left = insert (root->left, x);
    }
    else
    {
        root->right = insert (root->right, x);
    }
    

    Pay attention to that according to the C Standard the function main without parameters shall be declared like

    int main( void )