我编写了一个程序,该程序生成一个哈希表,然后在不再需要它时将其卸载。加载功能如下:
typedef struct node
{
char word[LENGTH + 1];
struct node *next;
}
node;
// Number of buckets in hash table
// Search time is improved with increased N (but sacrifice memory)
// djb2 hash function from http://www.cse.yorku.ca/~oz/hash.html
const unsigned int N = 100;
node *table[N];
bool load(const char *dictionary)
{
FILE *dictfile = fopen(dictionary, "r");
if (dictfile == NULL)
{
return false;
}
while (fscanf(dictfile, "%s", string) != EOF)
{
// Last error: 112 bytes in 2 blocks are still reachable in loss record 1 of 1: (file: dictionary.c, line: 101) [BELOW]
node *n = malloc(sizeof(node));
if (n == NULL)
{
return false;
break;
}
strcpy(n->word, string);
n->next = NULL;
if (table[hash(string)] == NULL)
{
table[hash(string)] = n;
}
else
{
n->next = table[hash(string)];
table[hash(string)] = n;
}
}
fclose(dictfile);
return true;
}
并在下面找到卸载功能:
bool unload(void)
{
for (int i = 0; i < N; i++)
{
while (table[i] != NULL) // if it's pointing to a node
{
node *tmp = table[i] -> next;
free(table[i]);
table[i] = tmp;
}
return true;
}
return false;
}
valgrind的输出告诉我,“丢失记录1(1 :(文件:dictionary.c,第102行)中的2个块中的112个字节仍然可以访问”),这对应于我的load函数中的malloc代码段。我不明白为什么会看到此消息,因为我以为我已经通过我的卸载功能释放了所有内存。这里发生了什么?