I think the issue lies with
Code:
struct node* i = p; //create iterator pointer
You originally have the local variable 'i' point to 'p'. Later on, you have 'i' point to some memory on the heap
Code:
i = talloc(); // allocates new 'struct node'
You then fill in the structure for 'i', but not for 'p' and then return what is pointed to by 'p'. Not withstanding indentation issues, I would probably do something like the following
Code:
struct node*
addword(struct node* p, char *w)
{
int cond;
if (p == NULL) {
p = talloc();
p->word = strdup(w);
p->left = p->right = NULL;
}else if ((cond = strcmp(w, p->word)) == 0) {
p->count++;
}else if (cond < 0)
p->left = addword(p->left, w);
else
p->right = addword(p->right,w);
}
return p;
}
I have the variable 'p' point to some memory on the heap. I then fill in the structure that is pointed to by 'p'. When 'p' returns, it points to the allocated memory.