Search code examples
cmemory-leaksvalgrind

Valgrind reporting memory definitely lost without errors


I am testing C code for memory leaks and can't seem to find the source of the leaks because there are 0 errors. Valgrind reports that there is a (quite significant) memory leak:

==30492== Memcheck, a memory error detector
==30492== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==30492== Using Valgrind-3.14.0.GIT and LibVEX; rerun with -h for copyright 
info
==30492== Command: ./a.out --leak-check=full --track-origins=yes
==30492== 
(This is where the input and output cases are displayed, which are a lot)
==30492== 
==30492== HEAP SUMMARY:
==30492==     in use at exit: 39,155 bytes in 167 blocks
==30492==   total heap usage: 380 allocs, 213 frees, 53,426 bytes allocated
==30492== 
==30492== LEAK SUMMARY:
==30492==    definitely lost: 20,480 bytes in 2 blocks
==30492==    indirectly lost: 2,064 bytes in 1 blocks
==30492==      possibly lost: 0 bytes in 0 blocks
==30492==    still reachable: 348 bytes in 9 blocks
==30492==         suppressed: 16,263 bytes in 155 blocks
==30492== Rerun with --leak-check=full to see details of leaked memory
==30492== 
==30492== For counts of detected and suppressed errors, rerun with: -v
==30492== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)

The code is written in a few files and consists of hundreds of lines, so posting it here would probably be a bit much. Could anyone explain what could be the problem here? Or would you need to see the actual code to give an answer? I can find only little documentation on valgrind and am quite stuck here.

(valgrind suggests to rerun with --leak-check=full, but that is what I did to get this output)


Solution

  • It is possible to get false positives (e.g. in shared library initializers, or things like libcrypto.so which does leak some allocation).

    However, you should always check - most likely you're forgetting some allocation.

    In your output, we can see:

     Command: ./a.out --leak-check=full --track-origins=yes
    

    This indicates you've invoked valgrind with:

    valgrind ./a.out --leak-check=full --track-origins=yes
    

    You should use this:

    valgrind --leak-check=full --track-origins=yes ./a.out
    

    If you find a leak (or other diagnostic) that you cannot control because it's internal to a third-party library, you can make a suppression file