如何解决Valgrind C中的内存测试错误内存泄漏问题
老实说,我不知道该如何解释,但是我的代码中存在内存泄漏。该代码通过了除此以外的所有测试。该功能是一个卸载功能,可以从内存中卸载字典。
// 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;
}
任何帮助将不胜感激!
解决方法
原来我忘了关闭文件!
// 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++;
}
fclose(file);
return true;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。