I'm getting a "double free or corruption" error when running this code. I don't know in which function the error is. I get the error after the code has run through check, before it gets to the unload function. If anyone could help that would be great.
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Represents a hash table
node *hashtable[N];
//Keeps track of the number of words inserted into the dictionary
int dic_count = 0;
// Hashes word to a number between 0 and 25, inclusive, based on its first letter
unsigned int hash(const char *word)
{
return tolower(word[0]) - 'a';
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Initialize hash table
for (int i = 0; i < N; i++)
{
hashtable[i] = NULL;
}
// Open dictionary
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
unload();
return false;
}
// Buffer for a word
char word[LENGTH + 1] = {'\0'};
// TODO
int innex = 0;
// Create a new node called header and set its value to NULL
node *head = malloc(sizeof(node));
// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
node *new_node = malloc(sizeof(node));
if(new_node == NULL)
{
unload();
return false;
}
else
{
strcpy(new_node->word, word);
innex = hash(new_node->word);
if(hashtable[innex] == NULL)
{
hashtable[innex] = new_node;
}
else
{
head = hashtable[innex];
hashtable[innex] = new_node;
new_node->next = head;
}
dic_count++;
}
free(new_node);
}
free(head);
// Close dictionary
fclose(file);
// Indicate success
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
// TODO
return dic_count;
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
// TODO
// Iterate through the hashtable and compare each word
int innex = hash(word);
node *cursor = hashtable[innex];
while(cursor != NULL)
{
if(strcasecmp(word, cursor->word))
{
printf("Word Found\n");
return true;
}
cursor = cursor->next;
}
printf("Word was not found\n");
return false;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
// TODO
node *cursor = NULL;
for(int i = 0; i < N; i++)
{
cursor = hashtable[i];
while(cursor != NULL)
{
node *tmp = cursor;
cursor = cursor->next;
free(tmp);
}
}
return false;
}