ok so i define my structure like this.
struct trie {
struct trie *child[26];
int count;
char letter;
};
the problem is when i try to fill my trie with words i get a segmentation fault.
ive been told that the problem is that the child variable isn’t pointing to anything and setting them to NULL would fix this. Also creating a second structure would be a good way to achieve this. i am new to C programming and am confused on how to create a second structure to achieve this. any help would be much appreciated.
int addWordOccurrence(const char* word)
{
struct trie *root;
root = (struct trie *)malloc(sizeof(struct trie*));
struct trie *initRoot=root;
int count;
int x=strlen(word);
printf("%d",x);
int i;
for(i=0; i<x; i++)
{
int z=word[i]-97;
if(word[i]=='\n')
{
z=word[i-1]-97;
root->child[z]->count++;
root=initRoot;
}
root->child[z] = (struct trie *)malloc(sizeof(struct trie));
root->child[z]->letter=word[i];
root->child[z]=root;
}
return 0;
}
This is problematic.
1) What if
child[z]was already set?2) You never set
child[z]->childorchild[z]->countto anything#2 is causing your segfaults, #1 is a memory leak.
My solution would be to write a function for allocating new children:
Then your code would become:
You also have to change the malloc of root:
Which is more clear, and avoids the errors I mentioned. http://codepad.org/J6oFQJMb No segfaults after 6 or so calls.
I’ve also noticed that your code
mallocs a newroot, but never returns it, so nobody except this function can ever see it. This is also a memory leak.