I am working on Pset5 and have successfully load dictionary into a trie. ( I tested it by printing out the size of dictionary, it says 143091, exactly the same as in the guide.)
struction of trie contains
{ bool is_word;
struct node* children[27]; }
However, my code hit segmentation fault on first try of check function. I looked into it via Valgrind, it turned out there is a invalid read of size 8 in "if (checker->children[position] == NULL)"
I used the same way as loading dictionary, couldn't see why it kept getting seg fault.
Please give a hint.
Many thanks
Here is the part of my code:
// creat a pointer to track the beginning of trie
node* root;
// dictionary size counter
int dictionary_size = 0;
// to initialize new nodes
void initialize(node* pointer)
{
pointer->is_word = false;
for(int i = 0; i < 27; i++)
{
pointer->children[i] = NULL;
}
}
// the Load function
bool load(const char* dictionary)
{
// open the dictionary file.
FILE* dt = fopen(dictionary, "r");
if (dt == NULL)
{
printf("Could not open %s.\n", dictionary);
return 1;
}
// creat a pointer at the start of tries to track loading.
node* root = malloc(sizeof(node));
initialize(root);
node* builder = root;
while (builder != NULL)
{
for (int ch = fgetc(dt); ch != EOF; ch = fgetc(dt))
{
if (isalpha(ch))
{
if (builder->children[ch - 'a'] == NULL)
{
node* new_node = malloc(sizeof(node));
initialize(new_node);
builder->children[ch - 'a'] = new_node;
}
builder = builder->children[ch - 'a'];
}
else if ( ch == '\'' )
{
if(builder->children[26] == NULL)
{
node* new_node = malloc(sizeof(node));
initialize(new_node);
builder->children[26] = new_node;
}
builder = builder->children[26];
}
// when hit \0
else
{
builder->is_word = true;
dictionary_size = dictionary_size + 1;
// reset the pointer to the root, preparing for a new word
builder = root;
}
}
// hit EOF, close dictionary
fclose(dt);
return true;
}
return false;
}
// the check function
bool check(const char* word)
{
node* checker = root;
// check spelling char by char
for (int j = 0; j < LENGTH + 1; j++)
{
if (isalpha(word[j]))
{
int position = (tolower(word[j]) - 'a');
printf("position:%i\n", position); //for test only.
if (checker->children[position] == NULL) //HERE COMES the INVALID READ
{
return false;
}
else
{
checker = checker->children[position];
}
}
else if (word[j] == '\'')
{
if (checker->children[26] == NULL)
{
return false;
}
else
{
checker = checker->children[26];
}
}
// when hit \0
else if (word[j] == '\0')
{
if (checker->is_word == true)
{
return true;
}
else
{
return false;
}
}
}
return false;
}