【问题标题】:Confused about freeing malloc memory in the loop对在循环中释放 malloc 内存感到困惑
【发布时间】:2021-08-11 08:44:07
【问题描述】:

我刚刚完成了 cs50 的 pset5,其中一个函数旨在将字典的内容加载到哈希表中。在所述函数的循环内,我必须为一个节点分配内存,稍后我将分配给哈希表中的节点。

当我尝试在每次循环迭代后释放节点 n 时,我的函数将不起作用。 当我不释放它时,它确实可以工作,更令人困惑的是,它还通过了 valgrind 检查和 cs50 的内存泄漏检查。

我的问题是:

  1. 我将如何释放“节点 n”以允许我的功能仍然工作?

  2. 当我不释放 'n' 时,为什么 valgrind 没有检测到任何内存泄漏?它是未定义行为的示例吗?

  3. 循环中的 malloc 是如何工作的,它是每次分配新的内存块还是覆盖之前的内存块?

任何答案将不胜感激。

代码如下:

bool load(const char *dictionary)
{

    //Setting counter to determine wheather node comes second in linked list or not.
    int counter = 0; 
    //declaring string array to store words from dictionary
    char word1[LENGTH +1]; 
    
    FILE *dic = fopen(dictionary, "r");
    if(dic == NULL)
    {
        return false;
    }
    //Loop loading words from dictionary to hash table
    while(fscanf(dic, "%s", word1) != EOF )
    {
        node *n = malloc(sizeof(node));
        if (n == NULL)
        {
            return false;
            free(n);
        }

        int i = hash(word1);
        //Storing word in temporary node
        strcpy(n->word, word1);
        n->next = NULL;
        //Three different conditions(first node of[i], second node of[i], and after second node of[i])
        if(table[i] == NULL)
        {
            table[i] = n;
            counter++;
            counter2++;
        }
        else if (counter == 1)
        {
            table[i]->next = n;
            counter = 0;
            counter2++;
        }
        else
        {

            n->next = table[i];
            table[i] = n;
            counter2++;
        }


    }
    
    fclose(dic);
    return true;

【问题讨论】:

    标签: loops malloc


    【解决方案1】:
    1. 您不会在加载时释放内存。你在卸载时释放它。这就是重点。

    2. 如果 valgrind 没有检测到内存泄漏,那么大概你有一个有效的卸载功能。为什么会是未定义的行为?

    3. 每次都会分配新的内存。如果不这样做,这将行不通。

    【讨论】:

    • 我想我刚刚明白,当我将指针 'node n' 分配给 'table[i]' 时,table[i] 会超过分配给 'node n' 的内存,对吗?那将解释一切。抱歉,我仍在思考一些基本概念。
    • @WojtekZ 是的,table[i] 拥有该内存的所有权。
    猜你喜欢
    • 2015-06-25
    • 2018-10-03
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    • 2015-11-07
    • 2016-07-13
    相关资源
    最近更新 更多