Search code examples
c++mallocvalgrindfree

Why does Valgrind not report any issue after not freeing malloc'd memory?


I'm trying to figure out why Valgrind does not emit any warning even if, in the following piece of code, there is no free after the malloc:

#include "stdlib.h"
#include "string.h"

char* ptr;

int main (int argc, char *argv[]) {
    ptr = static_cast<char*>(malloc(5 * sizeof(char)));
    strcpy(ptr, "test");
}

Is there some kind of "automatic free" I'm not aware of or am I missing something else?

Thanks.


Solution

  • It does report the issue, but to see it you need to run Valgrind with --leak-check=full --show-leak-kinds=all options:

    $ valgrind --leak-check=full --show-leak-kinds=all ./a.out
    ==317235== Memcheck, a memory error detector
    ==317235== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
    ==317235== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
    ==317235== Command: ./a.out
    ==317235== 
    ==317235== 
    ==317235== HEAP SUMMARY:
    ==317235==     in use at exit: 5 bytes in 1 blocks
    ==317235==   total heap usage: 2 allocs, 1 frees, 72,709 bytes allocated
    ==317235== 
    ==317235== 5 bytes in 1 blocks are still reachable in loss record 1 of 1
    ==317235==    at 0x483980B: malloc (vg_replace_malloc.c:309)
    ==317235==    by 0x40113E: main (1.cpp:7)
    ==317235== 
    ==317235== LEAK SUMMARY:
    ==317235==    definitely lost: 0 bytes in 0 blocks
    ==317235==    indirectly lost: 0 bytes in 0 blocks
    ==317235==      possibly lost: 0 bytes in 0 blocks
    ==317235==    still reachable: 5 bytes in 1 blocks
    ==317235==         suppressed: 0 bytes in 0 blocks
    ==317235== 
    ==317235== For lists of detected and suppressed errors, rerun with: -s
    ==317235== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
    

    Even if you run Valgrind without any options you can see the issue in HEAP SUMMARY section:

    ==317235==     in use at exit: 5 bytes in 1 blocks
    

    but without any more details.