C中的Valgrind内存测试错误。内存泄漏问题
Valgrind memory test error in C. Memory leak issue
老实说,我不知道该如何解释,但我的代码中存在内存泄漏。该代码通过了除此测试之外的所有测试。该函数是一个卸载函数,从内存中卸载字典。
// 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;
}
老实说,我不知道该如何解释,但我的代码中存在内存泄漏。该代码通过了除此测试之外的所有测试。该函数是一个卸载函数,从内存中卸载字典。
// 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;
}