My program compiles, but in debug50 it seems to get caught in a loop during the first strcpy in load.
Any suggestions would be great thanks.
// Implements a dictionary's functionality
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "dictionary.h"
// 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 = 5381;
// Hash table
node *table[N];
// Number of words in dictionary
int word_count = 0;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
// Hash word
int index = hash(word);
// Access linked list at index
// Traverse along list searching for word
for (node *tmp = table[index]; tmp != NULL; tmp = tmp->next)
{
if (strcasecmp(tmp->word, word) == 0)
{
return true;
}
}
return false;
}
// Hashes word to a number, code from http://www.cse.yorku.ca/~oz/hash.html
unsigned int hash(const char *word)
{
unsigned long hash = 5381;
int c;
while ((c = *word++))
{
hash = ((hash << 5) + hash) + c; /* hash * 33 + c */
}
return hash % N;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
// Open dictionary file
FILE *dict = fopen(dictionary, "r");
if (dict == NULL)
{
printf("Please enter a valid dictionary\n");
return false;
}
char new_word[LENGTH + 1];
// Read strings from file one at a time
while (fscanf(dict, "%s", new_word) != 0)
{
// Allocates memory for new node
node *n = malloc(sizeof(node));
if (n == NULL)
{
unload();
return false;
}
// Copies string to node
strcpy(n->word, new_word);
// Hashes word
int index = hash(new_word);
// Insert node into hash table at that location
// If there is no word at the index
if (table[index] == NULL)
{
table[index] = n;
n->next = NULL;
word_count++;
}
// If a list already exists
else
{
n->next = table[index];
table[index] = n;
word_count++;
}
}
fclose(dict);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
if (word_count > 0)
{
return word_count;
}
else
{
return 0;
}
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for (int i = 0; i < N; i++)
{
if (table[i] != NULL)
{
node *cursor = table[i];
node *tmp = table[i];
while (cursor != NULL)
{
cursor = cursor->next;
free(tmp);
tmp = cursor;
}
}
if (i == N - 1)
{
return true;
}
}
return false;
}