0

The following is my code for BST insert function.Could someone explain why this gives a segmentation fault?

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

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

struct node* insert(struct node* n,int age){
    if (n==NULL){
        n = malloc(sizeof(struct node));   
        n->value = age;
        n->left = n->right = NULL; 
    }
    else if(age < n->value){ 
        n->left = insert(n->left, age);
    }
    else {
        n->right = insert(n->right, age);
    }
    return n;
}

void main(){
    int age;
    struct node* n=NULL;
    scanf("%d",&age);
    while (age!=-1){
        n=insert(n,age);    
        scanf("%d",&age);
    }
}

I referred to this and it suggests the use of ** (reference to pointer).

f( &px );
//...

void f( int **px )
{
    *px = malloc( sizeof( int ) );

    printf( "*px = %p\n", *px );
}

But why can't we avoid the use of ** by changing the return type from void to node*?

Community
  • 1
  • 1

1 Answers1

1

This seems to work for me. I didn't change much or your code, except for how you are using scanf(), which doesn't end when you enter 1.

It is better to just call scanf once, and make sure you allow continuous input, using while (scanf(.....) == 1, to make sure that one value is always read until terminated, in this case, until age is 1.

Unless I am missing something, this is the proposed code:

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

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

struct node* insert(struct node* n,int age){
    if (n==NULL){
        n = malloc(sizeof(struct node));   
        n->value = age;
        n->left = n->right = NULL; 
    }
    else if(age < n->value){ 
        n->left = insert(n->left, age);
    }
    else {
        n->right = insert(n->right, age);
    }
    return n;
}

void
print_tree(struct node *n) {
    if (n != NULL) {
        print_tree(n->left);
        printf("%d\n", n->value);
        print_tree(n->right);
    }
}

int main(){
    int age;
    struct node* n = NULL;

    printf("Enter some numbers(1 to stop): ");
    while (scanf("%d", &age) == 1 && age != 1) {
        n = insert(n, age);
    }

    printf("\nYour numbers inserted into BST:\n");
    print_tree(n);

    return 0;
}
RoadRunner
  • 25,803
  • 6
  • 42
  • 75
  • I just changed my `void main()` to `int main()` and it works.Thanks!.But I fail to understand why `void` didn't work. – Alekhya Vellanki Dec 11 '16 at 09:21
  • 1
    This answer does not seem to fix any segfault. The code in the question, as it now stands, seems to be correct. Using `scanf` in the way that @RoadRunner suggests is a good idea, but not necessary. – nickie Dec 11 '16 at 09:22