I just can't get my speller program to work. I have been troubleshooting for several days with gdb, valgrind, testing different options etc. but I still have two basic problems.
All words are misspelled. I believe this is caused by an error in the check function. Valgrind tells me "Conditional jump or move depends on uninitialised value(s)" for the strcmp function.
The last word of the key text file is skipped which causes a seg fault. I thought the problem would be that I'm using eof as a loop condition in the load function. I tried using fgets instead but it didn't help.
I hope I'm not breaking any rules with this but below are my check and load functions. Any help will be very much appreciated. Thank you.
typedef struct node { char word [LENGTH+1]; struct node* next; } node; unsigned int counter = 0; node* hashtable[26]; //Hash function int hash_function(const char* key) { int hash = tolower(key[0])-'a'; return hash % 26; } /** * Returns true if word is in dictionary else false. */ bool check(const char* word) { int len = strlen(word); char low[len+1]; for (int i = 0; word[i] != '\0'; i++) { low[i] = tolower(word[i]); } low[len] = '\0'; int b = hash_function(low); node* cursor = hashtable[b]; while (cursor != NULL) { if(strcmp(low, cursor->word) == 0) { return true; } cursor = cursor -> next; } return false; } /** * Loads dictionary into memory. Returns true if successful else false. */ bool load(const char* dictionary) { //Initialize hash table for (int i = 0; i < 26; i++) { hashtable[i] = NULL; } //Open the dictionary FILE* inptr = fopen(dictionary, "r"); //Check if dictionary contains words if (inptr == NULL) { printf("File does not exist.\n"); return false; } //Check if end of dictionary is reached char buf[LENGTH+1]; while(fgets(buf, sizeof(buf), inptr) != NULL) { //Assign space for a new word node* new_node = malloc(sizeof(node)); //Copy word from buffer into new node strcpy(new_node->word, buf); new_node -> next = NULL; //Hash the word int a = hash_function(new_node->word); //Insert at beginning of linked list new_node->next = hashtable[a]; hashtable[a] = new_node; counter++; } fclose(inptr); return true; }