Valgrind claims there is unfreed memory. Is this bad?

后端 未结 7 1573
攒了一身酷
攒了一身酷 2021-01-06 13:15

Valgrind gives me the following leak summary on my code. However, I have freed all malloc\'ed memory. Is this a bad thing, or is this normal? My program is in c.

7条回答
  •  佛祖请我去吃肉
    2021-01-06 13:32

    Still reachable memory means that it is being pointed to by a global or static pointer. What you want to do is run valgrind with --show-reachable=yes to see whether it's a problem.

    Often times it's harmless and comes from a function like this:

    void foo()
    {
        static char *buffer = 0;
        if (buffer == 0)
        {
            buffer = (char *)malloc(...);
        }
    }
    

    That malloc will still be reachable. But no matter how many times foo is called, you allocate the buffer exactly once so there is no harm here in not freeing it.

    But consider a function like this:

    void foo()
    {
        static node_t *head = 0;
    
        node_t *node = (node_t *)malloc(sizeof(node_t));
        if (node)
        {
            node->next = head;
            head = node;
        }
        ...
    }
    

    Every time this function is called, another node will be allocated. While you may only leak a few nodes for your test runs, in a production run, you could leak enough that you run out of memory.

    One way to tell the difference is to see if different runs always leak the same memory or you leak more memory are test runs with larger inputs.

    But again, if you want to be safe, use --show-reachable=yes and see what's happening.

提交回复
热议问题