i don't know or understand through val grind where and what i'm doing wrong. Except for memory errors my code outputs as correct in check50.
my code
// Implements a dictionary's functionality
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include "dictionary.h"
// Represents number of buckets in a hash table
#define N 26
int quantity = 0;
// 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];
// 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];
// Insert words into hash table
while (fscanf(file, "%s", word) != EOF)
{
int position = hash(word);
node *a_node = malloc(sizeof(node));
if (hashtable[position] == NULL)
{
hashtable[position] = a_node;
strcpy(a_node->word, word);
a_node->next = NULL;
}
else
{
strcpy(a_node->word, word);
a_node->next = hashtable[position];
hashtable[position] = a_node;
}
quantity++;
}
// 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)
{
return quantity;
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int position = hash(word);
node *temp = hashtable[position];
while (temp != NULL)
{
if (strcasecmp(temp->word, word) == 0)
{
return true;
free(temp);
}
else
{
temp = temp->next;
}
}
return false;
free(temp);
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
node *temp = malloc(sizeof(node));
for (int i = 0; i < N ; i++)
{
temp = hashtable[i];
while (temp != NULL)
{
node *temp1 = temp;
temp = temp->next;
free(temp1);
}
free(temp);
}
return true;
}