【发布时间】:2021-01-03 02:21:36
【问题描述】:
老实说,我不知道如何解释这一点,但我的代码中存在内存泄漏。代码通过了除此之外的所有测试。该函数是一个从内存中卸载字典的卸载函数。
// Unloads dictionary from memory, returning true if successful else false
bool unload(void)
{
for ( int i = 0 ; i < N ; i++)
{
node *head = table[i];
node *cursor = head;
node *tmp = head;
while(cursor != NULL)
{
cursor = cursor->next;
free(tmp);
tmp = cursor;
}
}
return true;
}
这个函数加载字典:
// 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 false;
while (fscanf(file,"%s",word) != EOF)
{
node *n = malloc(sizeof(node));
if (n == NULL) return false;
strcpy(n->word,word);
n->next = NULL;
int hash_index = hash(word);
if (table[hash_index] == NULL)
{
table[hash_index] = n;
}
else
{
n->next = table[hash_index];
table[hash_index] = n;
}
total++;
}
return true;
}
任何帮助将不胜感激!
【问题讨论】:
-
如果可能的话,看看所有的 malloc 调用也会很有帮助。
-
@ViktorLatypov 抱歉,我已经编辑了帖子以显示加载功能。
标签: c data-structures hashtable cs50