Thread: Segmentation fault - creating binary tree

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    75

    Segmentation fault - creating binary tree

    i want to make binary tree program in c, but i am getting segmentation fault error.. my code is this...

    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
    typedef struct node {
        int data;
        struct  node* left;
        struct node* right;
    }node;
    
    
    int n;
    
    
    int main()
    {
        node *root, *first, *current, *temp; int num,i;
        printf("How many no.\n");
        scanf("%d", &n);
        first = root;
        printf("Enter no.");
        scanf("%d", &root->data);
        for(i=1;i<n;i++) {
            current=first;
            temp = (node*)malloc(sizeof(node));
    
    
            printf("Enter no.");
            scanf("%d", &num);
            temp->data=num;
            if(num<current->data) {
                current->left=temp;
            }
            else current->right=temp;
        first=current;
    
    
        }
        return 0;
    }
    i am getting error at this line
    Code:
            temp = (node*)malloc(sizeof(node));
    can anyone tell me what is wrong. and how can i write crud operation on binary tree

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    You forgot to allocate space for the root node before you used scanf to read into root->data.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Aug 2015
    Posts
    75
    Quote Originally Posted by laserlight View Post
    You forgot to allocate space for the root node before you used scanf to read into root->data.
    Thank you very much..now its working

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 06-09-2016, 10:45 PM
  2. Segmentation Fault-Binary Search Tree
    By thriller500 in forum C++ Programming
    Replies: 2
    Last Post: 11-08-2012, 02:00 AM
  3. Creating a Binary Search Tree
    By paranoidgnu in forum C Programming
    Replies: 1
    Last Post: 07-14-2011, 11:54 AM
  4. help with segmentation fault, binary tree
    By archibald627 in forum C Programming
    Replies: 7
    Last Post: 02-10-2011, 12:30 PM
  5. creating a binary search tree
    By krishpatel in forum C Programming
    Replies: 1
    Last Post: 12-23-2010, 01:18 PM

Tags for this Thread