Search code examples
c++memory-leaksvalgrind

How can i explicitly hint Valgrind about intentially non freed memory


I have a good number of memory allocations i just want to let die with the process because of complicated synchronisation issues and other convenience.

I don't want to write a suppression file.

Is there some C code that i can signal this to avoid false positives (not really false but unwanted). I know valgrind has an API but failed to find that.


Solution

  • One easy way to quiet valgrind would be store your "leaked" pointers in a process-lifetimed data structure so that valgrind reports them as "still reachable" rather than "definitely leaked". For example, in the code below, I call IgnoreThisLeak(leakMe) to keep valgrind from complaining that I never free my 100-byte allocation:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct Node
    {
       struct Node * _nextNode;
       void * _leakPtr;
    };
    
    static void IgnoreThisLeak(void * leakPtr)
    {
       static struct Node * _tail = NULL;
    
       struct Node * n = malloc(sizeof(struct Node));
       n->_nextNode = _tail;
       n->_leakPtr  = leakPtr;
       _tail = n;
    }
    
    int main(int argc, char ** argv)
    {
        int * leakMe = malloc(100);
    
        IgnoreThisLeak(leakMe);
        printf("leakMe=%p\n", leakMe);
        return 0;
    }