当我运行 valgrind 检查内存泄漏时,我得到了一些错误,尽管它说我调用 malloc 的次数与 free 相同,这应该意味着我释放了所有内存。
// Implements a dictionary's functionality
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dictionary.h"
// Represents a node in a hash table
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// TODO: Choose number of buckets in hash table
const unsigned int N = 26;
int count = 0;
// Hash table
node *table[N];
// Returns true if word is in dictionary, else false
bool check(const char *word)
{
node *cursor = malloc(sizeof(node));
cursor->next = table[hash(word)]->next;
while(cursor->next != NULL)
{
if(strcmp(cursor->word, word) == 0)
{
free(cursor);
return true;
}
else
{
cursor = cursor->next;
}
}
// TODO
free(cursor);
return false;
}
// Hashes word to a number
unsigned int hash(const char *word)
{
// TODO: Improve this hash function
char c = toupper(word[0]) - 65;
return c;
}
// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
for(int i = 0; i <= 25; i++)
{
table[i] = malloc(sizeof(node));
}
char word[LENGTH];
FILE *file = fopen(dictionary, "r");
if (file == NULL)
{
fclose(file);
return false;
}
while(fscanf(file, "%s", word) != EOF)
{
fscanf(file, "%s", word);
count++;
if(table[hash(word)] == NULL)
{
node *n = malloc(sizeof(node));
n->next = NULL;
table[hash(word)]->next = *&n;
strcpy(n->word, word);
}
else
{
node *n = malloc(sizeof(node));
n->next = table[hash(word)]->next;
table[hash(word)]->next = *&n;
strcpy(n->word, word);
}
}
fclose(file);
// TODO
return true;
}
// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
// TODO
return count;
}
// Unloads dictionary from memory, returning true if successful, else false
bool unload(void)
{
node *cursor = malloc(sizeof(node));
node *cursor2 = malloc(sizeof(node));
for(int i = 0; i <= 25; i++)
{
cursor->next = table[i]->next;
do
{
cursor2->next = cursor->next->next;
if(cursor2->next == NULL)
{
free(cursor->next);
break;
}
free(cursor->next);
cursor->next = cursor2->next;
}
while(true);
}
free(cursor);
free(cursor2);
for(int i = 0; i <= 25; i++)
{
free(table[i]);
}
return true;
// TODO
}
到目前为止,我尝试将表数组中的所有节点设置为空,这给了我一个分段错误,所以我改为在表数组中的每个节点上调用 malloc(sizeof(node)) 。我试过这个,因为我注意到它提到了未初始化的值。 Valgrind 还提到了一些关于无效的 free() 的事情,我不太明白。我对编码和制作数据结构还是很陌生,这也是我在蚂蚁编码论坛上发表的第一篇寻求任何形式帮助的帖子,因为此时我完全卡住了,所以我很抱歉这篇帖子(可能)格式错误,建议受欢迎的。谢谢。