Segmentation fault creating a binary search tree in C -
i started learning trees in c , keep getting segmentation fault code. code meant create tree return smallest , biggest values in tree. have looked @ other peoples code , can't seem find mistake making. if can spot helpful.
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node{ int data; struct node* right; struct node* left; }node; node* insert(node* root, int data); int min(node* root); int max(node* root); node* getnewnode(int data); int main(void){ int min, max, data, x; node* root = null; printf("how many elements in tree\n"); scanf("%i", &x); for(int = 0; < x; i++){ scanf("%i", &data); root = insert(root, data); } min = min(root); max = max(root); printf("the min value %i, , max value %i\n", min, max); } node* insert(node* root, int data){ if(root == null){ root = getnewnode(data); } else if(data <= root->data){ root->left = insert(root->left, data); } else{ root->right= insert(root->right, data); } return root; } node* getnewnode(int data){ node* newnode = (node*)malloc(sizeof(node*)); newnode->data = data; newnode->left = newnode->right = null; return newnode; } int min(node* root){ node* temp = root; if(root->left == null){ return root->data; } else{ return min(root->left); } } int max(node* root){ node* temp = root; if(root->right == null){ return root->data; } else{ return max(root->right); } }
this line :
node* newnode = (node*)malloc(sizeof(node*));
you allocating sizeof(node *)
bytes size of pointer system. want allocate enough memory hold the structure itself , not pointer it. work :
node* newnode = (node*)malloc(sizeof(node) * sizeof(char));
Comments
Post a Comment