Reputation: 3755
Based on my current understanding it's something related to not allocating memory properly.
I don't understand why can it print item->key and not call the compare function? The struct item* item is already in the memory I guess?
Any advice? been stuck for quite awhile
struct item
{
char* key;
struct item *left;
struct item *right;
};
int compare(char* A, char* B){
return strcmp(A, B);
}
struct item* insert(struct item* item, char* key)
{
printf ("(%s):",key);
printf ("(%s)\n",item->key); // I can do Node->Key here
compare(item->key, key); // I cant do node->key here // Segmentation Error
}
Potential fix? I tried allocating it a memory and loading the item into it. Still the same result too. Just trying anything I can find :(
struct item* item = (struct item*) malloc(sizeof(struct item));
Upvotes: 0
Views: 29
Reputation: 62045
After your clarification about what is being printed, the only thing I can guess is that your compiler is trolling you, and the segfault is not really happening in your invocation of compare(item->key, key);
but within strcmp()
.
printf()
checks for null arguments, so if item->key
is null, then printf()
will print "null
". On the other hand, strcmp()
does not check for null
, and it will crash if you pass null
to it. A crash on compare()
just does not make any sense at all.
Of course it should be noted that compilers are not known to troll people. There must be a better explanation.
Upvotes: 1
Reputation: 23058
You did initialize item
, but you didn't assign item->key
properly. item->key
still points to somewhere uninitialized.
Upvotes: 1