pointers - Implement BST in c: segmentation fault -


i'm trying implement binary search tree in c. use lldb trace code , found out when function put return, return node pointer key = 5 , value = 9, , assigned node pointer p in main.

however when pass tree_walk function , try print out everything, gave me segmentation fault. can please tell wrong code. thank you

typedef struct node{     int key;     int value;     int size;     struct node *left;     struct node *right; }node;  node* put(node **node, int k, int val){     if(*node == null){         node *newnode = (node *)malloc(sizeof(node*));         newnode->key = k;         newnode->value = val;         return newnode;     }else if((*node)-> key == k){         (*node)->value = val;     }else{          int cmp = k > ((*node)->key) ? 1 : 0;          node **ptr = null;          if(cmp == 1){             ptr = &((*node)->right);             (*node)->right = put(ptr, k, val);         }else{             ptr = &((*node)->left);             (*node)->left = put(ptr, k ,val);         }     }     (*node)->size = size((*node)->left) + size((*node)->right) + 1;     return *node; }  int main(void){      node *p = null;     p = put(&p, 5,9);     tree_walk(p); } 

this line allocates wrong size:

node *newnode = (node *)malloc(sizeof(node*)); 

it should be:

node *newnode = malloc( sizeof *newnode ); 

you allocated enough space pointer, not node.

another problem never initialize newnode->left , newnode->right. if tree_walk function tries read them causes undefined behaviour.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -