I tried so many times and fixed somehow based on reply. This is a little embarrassing but I still cannot figure it out. There must be some problems in load and check.
#include "dictionary.h"
typedef struct node
{
char word[LENGTH + 1];
struct node* next;
}node;
int hash_function(char* key)
{
int hash = tolower(key[0]) - 'a';
return hash % 26;
}
node* hashtable[26];
int sizes = 0;
/**
* Returns true if word is in dictionary else false.
*/
bool check(const char* word)
{
int s = strlen(word);
char checker[LENGTH + 1];
for(int i = 0; i < s; i++)
{
checker[i] = tolower(word[i]);
}
int b = hash_function(checker);
node* crawler = hashtable[b];
while(crawler != NULL)
{
if (strcmp(checker, crawler->word) == 0)
{
return true;
}
else
crawler = crawler -> next;
}
return false;
}
/**
* Loads dictionary into memory. Returns true if successful else false.
*/
bool load(const char* dictionary)
{
FILE* file = fopen(dictionary, "r");
if (file == NULL)
{
return false;
}
while(feof(file) != 0)
{
printf("start load.\n");
node* new_node = malloc(sizeof(node));
fscanf(file, "%s", new_node->word);
int a = hash_function(new_node-> word);
if (hashtable[a] == NULL)
{
hashtable[a] = new_node;
new_node -> next = NULL;
sizes++;
}
else if(hashtable[a] != NULL)
{
new_node->next = hashtable[a];
hashtable[a] = new_node;
sizes++;
}
}
return true;
}
/**
* Returns number of words in dictionary if loaded else 0 if not yet loaded.
*/
unsigned int size(void)
{
// TODO
return sizes;
}
/**
* Unloads dictionary from memory. Returns true if successful else false.
*/
bool unload(void)
{
for(int i =0; i < 27; i++)
{
node* cursor = hashtable[i];
while(cursor != NULL)
{
node* temp = cursor;
cursor = cursor->next;
free(temp);
}
}
return true;
}
WORDS MISSPELLED: 19190
WORDS IN DICTIONARY: 0
WORDS IN TEXT: 19190
TIME IN load: 0.01
TIME IN check: 0.11
TIME IN size: 0.00
TIME IN unload: 0.00
TIME IN TOTAL: 0.12
==32145==
==32145== HEAP SUMMARY:
==32145== in use at exit: 568 bytes in 1 blocks
==32145== total heap usage: 2 allocs, 1 frees, 1,136 bytes allocated
==32145==
==32145== LEAK SUMMARY:
==32145== definitely lost: 0 bytes in 0 blocks
==32145== indirectly lost: 0 bytes in 0 blocks
==32145== possibly lost: 0 bytes in 0 blocks
==32145== still reachable: 568 bytes in 1 blocks
==32145== suppressed: 0 bytes in 0 blocks
==32145== Rerun with --leak-check=full to see details of leaked memory
==32145==
==32145== For counts of detected and suppressed errors, rerun with: -v
==32145== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)