My code is having segmentation fault (core dumped) here. I'm not pretty sure which line is causing it since I'm pretty new to C. What I am trying to do here is to implement a binary search tree for each line on the file (only for insertion and search). Each line will not be more than 1000 words.
Here's my code:
BST *bst_ins(BST *bst, char *key, void *value)
{
BST* temp = NULL;
int cmp = strcmp(bst->kvp.key, key);
if(bst == NULL)
{ /* This for null node */
temp = (BST*)malloc(sizeof(BST)); /* allocate the memory of struct for new node */
temp->left = NULL;
temp->right = NULL;
temp->kvp.key = key;
temp->kvp.value = value;
}
else if(cmp < 0) /* Current node less than input */
{
bst->right = bst_ins(bst->right,key,value);
}
else if(cmp > 0)
{
bst->left = bst_ins(bst->left,key,value);
}
return bst;
}
KVP *bst_get(BST *bst, char *key)
{
KVP* return_this;
if(bst!=NULL)
{
if(bst->kvp.key==key)
{
return return_this;
}
else if(strcmp(bst->kvp.key, key) < 0) /* Current node less than input */
{
return bst_get(bst->left, key);
}
else if(strcmp(bst->kvp.key,key) > 0)
{
return bst_get(bst->right,key);
}
}
return 0;
}
Below is header.h
typedef struct {
char *key;
void *value;
} KVP;
typedef struct bst {
struct bst *left;
struct bst *right;
KVP kvp;
} BST;
Could someone please help me figure out which line is causing it? Thanks.
EDIT:
SOLVED! FINALLY :D
Here's the main function.
int main()
{
char* str1=strdup("alokama");
char* str2=strdup("kokokoko");
BST *bst = NULL;
bst = bst_insert(bst,str1,NULL);
bst = bst_insert(bst,str2,NULL);
if(bst_get(bst,str1)){ printf ("yuhuu\n"); }
return 0;
}