// Implements a dictionary's functionality
#include <stdio.h>
#include <stdbool.h>
#include <ctype.h>
#include <string.h>
#include <strings.h>
#include <stdlib.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 = 26;
// Hash table
node *table[N];
//num of words
int NumOfWords = 0;
// Returns true if word is in dictionary else false
bool check(const char *word)
{
node *word_checker = malloc(sizeof(node));
int hash_position = hash(word);
word_checker = table[hash_position];
while(word_checker != NULL)
{
if( strcasecmp(word_checker->word, word) == 0)
{
free(word_checker);
return true;
}
word_checker = word_checker->next;
}
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
int hash_index = 0;
for(int i = 0; word[i] != '\0'; i++)
{
if(isalpha(word[i]))
{
hash_index += word[i];
}
}
return hash_index % N;
}
// Loads dictionary into memory, returning true if successful else false
bool load(const char *dictionary)
{
char word[LENGTH + 1];
FILE *file = fopen(dictionary, "r");
if(file == NULL)
{
return 1;
}
while(fscanf(file, "%s", word) != EOF)
{
node *new_node = malloc(sizeof(node));
if(new_node == NULL)
{
return false;
}
strcpy(new_node ->word, word);
new_node ->next = NULL;
int index = hash(word);
if(table[index] == NULL)
{
table[index] = new_node;
}
else
{
new_node ->next = table[index];
table[index] ->next = new_node;
}
NumOfWords++;
}
fclose(file);
return true;
}
// Returns number of words in dictionary if loaded else 0 if not yet loaded
unsigned int size(void)
{
return NumOfWords;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for(int i = 0; i < N; i++)
{
node *cursor = NULL;
cursor = table[i];
while (cursor != NULL)
{
node *tmp = cursor;
cursor = cursor->next;
free(tmp);
}
}
return true;
}
错误消息是:[1]:https://i.stack.imgur.com/pabnG.png
此外,valgrind表示在行110上无效读取了大小8(cursor = cursor-> next;)。 它还会敏感地检查单词的大小写,这不是我想要的。我试过使用strcasecmp,但无济于事。 我仍然对stackoverflow还是陌生的,所以请原谅一些格式化方面的小错误。