I use a simple (or so I thought) code to load the dictionary, no optimization. Yet I keep getting into segmentation fault. In this example I use the small dictionary, which only has 2 words. In my code, I would have expected my while() loop to run 2 times. Using gdb, however, I seem to have found that the while() loop always run 3 times instead. Thus, the 3rd time it runs, it seems to load up N->word with Null value, then messes up the value variable to a negative value (value becomes (0 - 97)%26, which then messes up the next 2 pointer assignment sentences. That's my understanding, but I'm not sure how to fix it. Help appreciated.
bool load(const char* dictionary)
{
// Initializes a hash table made up of pointers to singly linked lists
for (int i = 0; i < n; i++)
{
table[i] = malloc(sizeof(node));
table[i] -> next = NULL;
}
//set up to load dictionary
FILE *ptr = fopen(dictionary,"r");
//The hash function simply modulus the first letter and put the words into linked lists corresponding to 26 buckets
while (fgetc(ptr) != EOF)
{
node *N = malloc(sizeof(node));
fscanf(ptr,"%s",N->word);
int value = (N->word[0] - 97) % n;
//insert the new node into the beginning of the linked list ie. linked list kinda sorted backwards!
N->next = table[value]->next;
table[value]->next = N;
}
return true;
}