insert - Keep getting a seg fault with my binary search (working in C) -
i'm having trouble getting binary tree work. 1 weird thing when try print node data repeatedly, seg fault. i'm taking red flag i'm doing wrong. test program made struct definition , insertion function. notice issue?
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <stdbool.h> typedef struct tnode{ char *name; int value; struct tnode *left; struct tnode *right; } tnode; tnode *insert(tnode *node, char *name, int value){ if(node==null){ tnode *temp = malloc(sizeof(struct tnode)); temp->name = strdup(name); temp->value = value; temp->left = null; temp->right = null; return temp; } else if(strcmp(name,node->name)<0) { node->left = insert(node->left, name, value); } else if(strcmp(name,node->name)>0) { node->right = insert(node->right, name, value); } else{ printf("something went wrong\n"); } } int main(){ tnode *root = null; root = insert(root,"george",11); root = insert(root,"dick",12); root = insert(root,"walter",13); root = insert(root,"harry",13); printf("%s\n",root->name); root = insert(root,"zink",40); printf("%s\n",root->name); }
the "insert" function not return anything, except in first if (node==null)
case. when you're not returning function supposed return value, behavior undefined; may segfault, or may appear run on else's system, etc.
for cases besides if (node==null)
case, want return node;
. or, may want abort()
or exit()
or in "something went wrong" case. should return 0;
main, that's not causing problem.
these issues easier notice if compile warnings turned on. compilers (e.g. gcc), can turn on many warnings passing -wall flag compiler. recommend compiling @ least -wall.
Comments
Post a Comment