HELP!! I'm finally able to make my code compile without error. I know it won't guarantee it'll work, but at least I can move to the next step. :-) When I run the code it gives me segmentation fault in line 103.
if(trav->children[index] == NULL (It's the code before 'calloc'-ing children's node)
Below is my 'load' code. Can someone please kindly tell me what's wrong with it? Thanks beforehand. One more question, how do we run gdb for this task? I tried gdb speller it comes back with no executable file. Debug50 doesn't really give me much details beside jumping over lines of codes and spit segfault. Or maybe it's just me that don't know how to use it properly. Hehehe
/**
* Loads dictionary into memory. Returns true if successful else false.
* Here I use trie tree
*/
bool load(const char* dictionary)
{
// open dictionary
FILE* dic = fopen(dictionary, "r");
// if unsuccessful do not continue
if(dic == NULL)
{
printf("Could not open %s.\n", dictionary);
return false;
}
// allocate memory to root
for(int i = 0; i < ALPHABETS; i++)
{
root = NULL;
root = (node*)calloc(1, sizeof(node));
}
// if unsuccessful do not continue
if(root == NULL)
{
printf("calloc failed\n");
return false;
}
// initiate trav pointer
trav = root;
// read each dictionary word letter by letter and record in trie
for(int key = fgetc(dic); key != EOF; key = fgetc(dic))
{
while(key != '\n')
{
for(int index = 0; index < ALPHABETS; index++)
{
if(trav->children[index] == NULL)
{
trav->children[index] = (node*)calloc(1, sizeof(node));
// if unsuccessful
if(trav->children[index] == NULL)
return false;
}
if(isalpha(key))
trav = trav->children[key - 'a'];
if(key == '\'')
trav = trav->children[key];
if(key == '\0')
{
trav = trav->children[key];
trav->is_word = true;
n++;
}
}
key++;
}
trav = root;
key++;
return true;
}
// close source file
fclose(dic);
return false;
}