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;
}