#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <strings.h>
#include "dictionary.h"
int s = 0;
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
const unsigned int N = 45;
// Hash table
node *table[N];
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int hsh = hash(word);
node *cursor = table[hsh];
while (cursor != NULL)
{
if(strcasecmp(cursor->word, word) == 0)
{
return true;
}
else
{
cursor = cursor->next;
}
}
return false;
}
// Hashes word to a number (using first two letters)
unsigned int hash(const char *word)
{
int n = strlen(word) - 1;
return n;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
FILE *dict = fopen(dictionary, "r");
if (!dict)
{
return false;
}
char *tempword = malloc((LENGTH + 1) * sizeof(char));
while (fscanf(dict, "%s", tempword) != EOF)
{
node *n = malloc(sizeof(node));
if (n == NULL)
{
return false;
}
strcpy(n->word, tempword);
int hsh = hash(tempword);
n->next = table[hsh];
table[hsh] = n;
s++;
free(n);
}
free(tempword);
fclose(dict);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return s;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for (int i = 0; i < N; i++)
{
node *cursor = table[i];
while (cursor != false)
{
node *tmp = cursor->next;
free(cursor);
cursor = tmp;
}
}
return true;
}
Amongst other valgrind errors, I always get invalid read of size 1 at line 33 (if(strcasecmp(cursor->word, word) == 0)). Using debug50 I have not been able to work out why this is but I have noticed that the else bracket a few lines later is not updating the cursor. I hope this is clear enough and thanks in advance for any help :)