After completing load, I'm working on the check function. My implementation compiles but leads to a segmentation fault with various dictionaries and text files. My load function works, and the program prints MISSPELLED WORDS right before crashing.
GDB indicates that the problem occurs at the first line where my traversal pointer checks if the node found at the index value is NULL.
if (trav->children[index] == NULL)
Is there an issue with scope between my load and check functions? What else could be causing the segmentation fault?
Here is my code:
// define struct
typedef struct node
{
bool is_word;
struct node* children[27];
}
node;
node* root = NULL;
node* trav = NULL;
bool check(const char* word)
{
// initialize variable
node* trav = root;
unsigned int index = 0;
// loop through chars in array
for (int i = 0; i < strlen(word); i++) // n = strlen
{
if (isalpha(word[i]))
{
index = tolower(word[i]) - 'a';
}
else if (word[i] == '/')
{
index = 26;
}
// check child element
if (trav->children[index] == NULL)
{
return false;
}
else if (trav->children[index] != NULL && i != strlen(word) - 1)
{
trav = trav->children[index];
}
else if (i == strlen(word) - 1)
{
return trav->is_word;
}
}
return false;
}
bool load(const char* dictionary)
{
// open input file
FILE* dicptr = fopen(dictionary, "r");
if (dicptr == NULL)
{
printf("Could not open %s.\n", dictionary);
return false;
}
// create root, initiate childrem to NULL
node* root = (struct node*)calloc(1, sizeof(node));
node* trav = root;
//iterate throught trie
unsigned int index = 0;
for (unsigned int c = fgetc(dicptr); c != EOF; c = fgetc(dicptr))
{
if (c == '\n')
{
trav->is_word = true;
trav = root;
index = 0;
}
else if (isalpha(c))
{
tolower(c);
index = c - 'a';
if (trav->children[index] == NULL)
{
trav->children[index] = (struct node*)calloc(1, sizeof(node));
trav = trav->children[index];
}
else if (trav->children[index] != NULL)
{
trav = trav->children[index];
}
}
else if (c == '/' && index > 0)
{
index = 26;
if (trav->children[index] == NULL)
{
trav->children[index] = (struct node*)calloc(1, sizeof(node));
trav = trav->children[index];
}
else if (trav->children[index] != NULL)
{
trav = trav->children[index];
}
}
}
fclose(dicptr);
return true;
}