我的代码可以编译并执行我想要的操作,但是valgrind
总是吐出一点我不明白的错误。就是说我正在尝试使用未初始化的变量,但是它们已经非常清楚地初始化了。即使定义了变量,它也指出它尚未初始化。
很明显,我的代码可以工作,所以我不明白真正的问题是什么。我什至在网上看过别人的解决方案,我的代码似乎匹配。 valgrind
只是讨厌我吗?发生了什么事?
我的代码:
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "dictionary.h"
// Represents number of buckets in a hash table
#define N 26
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Represents a hash table, AKA an array of nodes
node *hashtable[N];
// Number of Words loaded into memory
int wordnum = 0;
// Initialize custom functions to be defined later
unsigned int hash(const char *word);
bool load(const char *dictionary);
unsigned int size(void);
bool check(const char *word);
bool unload(void);
// 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)
{
// 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 index = hash(word) % N;
if (hashtable[index] == NULL)
{
hashtable[index] = malloc(sizeof(node));
for (int i = 0, n = strlen(word); i < n; i ++)
{
hashtable[index]->word[i] = word[i];
}
hashtable[index]->next = NULL;
wordnum++;
}
else
{
node *new_node = malloc(sizeof(node));
for (int i = 0, n = strlen(word); i < n; i ++)
{
new_node->word[i] = word[i];
}
new_node->next = hashtable[index];
hashtable[index] = new_node;
wordnum++;
}
}
// 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 wordnum;
}
// Returns true if word is in dictionary else false
bool check(const char *word)
{
int index = hash(word);
node *current = hashtable[index];
while (current != NULL)
{
char tempword [LENGTH + 1];
strcpy(tempword, word);
for (int i = 0, n = strlen(tempword); i < n; i ++)
{
tempword[i] = tolower(tempword[i]);
}
if (strcmp(tempword, current->word) == 0)
{
return true;
}
current = current->next;
}
return false;
}
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for (int i = 0; i < N; i ++)
{
while (hashtable[i] != NULL)
{
node *buffer = hashtable[i];
hashtable[i] = hashtable[i]->next;
free(buffer);
}
}
for (int i = 0; i < N; i ++)
{
if (hashtable[i] != NULL)
{
return false;
}
}
return true;
}
答案 0 :(得分:0)
在加载时,如果您发现要存储的单词,则会初始化hashtable[index]
。在卸载时,您尝试释放所有哈希表节点。如果字典中没有以“ z”开头的单词怎么办?然后hashtable[25]
未初始化,并且valgrind会抱怨。
您知道CS50 has a stack forum对于CS50 pset有很多疑问和答案吗?