Below is the code from my spellchecker load procedure; other parts of the code omitted. When I use a small dictionary, everything seems to run fine, but when I try to load the large dictionary, I get a Segmentation Fault error.
I have tried running valgrind, and it points at the four lines where I use the command
currentNode -> children[letterIndex]
but I don't understand why what I am doing is wrong, especially since it works with a smaller dictionary that I am testing.
unsigned int wordCount = 0;
typedef struct node
{
bool isAWord;
struct node* children[numChildren];
}
node;
struct node* rootNode;
bool load(const char* dictionary)
{
FILE* fp = fopen(dictionary, "r"); //Opening up the dictionary
if (fp == NULL)
{
printf("Could not open %s.\n", dictionary);
return false;
}
rootNode = calloc (1, sizeof(node)); //setting up the rootNode; calloc clears the memory as well as allocating
struct node* currentNode = rootNode;
int letterIndex = 0;
for (int c = fgetc(fp); c != EOF; c = fgetc(fp)) //stepping through the whole file, like in speller
{
if (isalpha(c) || c =='\'') // if it's a letter or an apostrophe
{
letterIndex = c - '\''; //sets index to 0 if apostrophe, 1-26 for the letters
if (currentNode -> children[letterIndex] == NULL)
{
currentNode -> children[letterIndex] = calloc (1, sizeof(node)); //create a new node and go there
currentNode = currentNode -> children[letterIndex];
}
else
{
currentNode = currentNode -> children[letterIndex]; //just go there
}
}
else //not a letter/apostrophe, so end of the line; set isAWord true, increment wordcount, and make current = root
{
currentNode -> isAWord = true;
wordCount++;
currentNode = rootNode;
}
}
printf("\n%i\n", wordCount); //Just for testing - make sure to remove when submitting
fclose(fp); //close down the dictionary
// TODO
return true;
}
The dictionary list that I am using is: cat caterpillar dickie dickie's pinochle emuification delta foxtrot hotel hotel's meatloaf
I don't know if that makes a difference, but I'm trying to be thorough. Any help/suggestions would be greatly appreciated, because I'm also having a segfault problem with my check function, and I think I need to get this one fixed first.
Thanks,
-Brian