pointers - C - Segmentation Fault while Creating Binary Tree Using recursion -


i trying write simple program of creating binary tree using pointers in c , unable find problem code. receiving segmentation fault on second insertion.

the program takes input of 5 numbers , creates binary tree using array input.sample run :

here output of program

enter 5 elements :

45 78 89 32 46

in generatebst

in insert going right sub tree

in insert

segmentation fault

please me resolve error. thank you.

#include <stdio.h> #include <stdlib.h>  typedef struct node {     int value;     struct node * lst;     struct node * rst; }node;  void printbst(node *root){     puts("in printbst");     if(root == null){         return;     }     printbst(root->lst);     printf(" %d ", root->value);     printbst(root->rst); }  void insert(node **root, int element){     puts("in insert");     if((*root)->value > element){         puts("going left sub tree");         insert(&(*root)->lst ,element);     } else if ((*root)->value < element) {         puts("going right sub tree");         insert(&(*root)->rst ,element);     } else {         puts("creating new node insert");         node * newnode = (node*)malloc(sizeof(node));         newnode->value = element;         newnode->lst = null;         newnode->rst = null;         (*root) = newnode;     } }  node* generatebst(int *elements, int n){     puts("in generatebst");     int =0;     node * root = null;     root = (node*)malloc(sizeof(node));     root->value = *(elements);     root->lst = null;     root->rst = null;     for(i=1; < n; i++){         insert(&root, *(elements+i));     }     return root; }  int main(){     node * root = null;     int = 0, element, *elements ;     elements = (int*)malloc(sizeof(int)*5);     puts("enter 5 elements : ");     fflush(stdin);     for(i = 0; < 5; i++){         scanf("%d",&element);         elements[i] = element;     }     root = generatebst(elements,5);     printbst(root);     //deallocbst(root);     return 0; } 

just found problem using gdb. have error on line 22. problem don't check whether root null or not problem insertion of first element.

to run program through gdb compile , run using:

g++ -g yourporgram.cpp gdb a.out run 

when programs stops (segfaultor other problems) type:

bt 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -