Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to use Valgrind Memcheck

📅 2020-Jan-15 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ ⬩ 📚 Archive

Memcheck is the most commonly used tool in Valgrind. It can be used to detect memory leaks and errors in your programs.

$ valgrind ./a.out
$ valgrind --tool=memcheck ./a.out

This should report any leaks.

$ valgrind --leak-check=full ./a.out

Example

Here is an example C++ program which is forgetting to free 12 bytes of memory:

int main()
{
    int * vp = new int[3];
    return 0;
}

When we compile and run the binary with valgrind, we see this report of a memory leak:

$ valgrind  ./a.out
==1855== Memcheck, a memory error detector
==1855== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1855== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==1855== Command: ./a.out
==1855==
==1855== error calling PR_SET_PTRACER, vgdb might block
==1855==
==1855== HEAP SUMMARY:
==1855==     in use at exit: 12 bytes in 1 blocks
==1855==   total heap usage: 2 allocs, 1 frees, 72,716 bytes allocated
==1855==
==1855== LEAK SUMMARY:
==1855==    definitely lost: 12 bytes in 1 blocks
==1855==    indirectly lost: 0 bytes in 0 blocks
==1855==      possibly lost: 0 bytes in 0 blocks
==1855==    still reachable: 0 bytes in 0 blocks
==1855==         suppressed: 0 bytes in 0 blocks
==1855== Rerun with --leak-check=full to see details of leaked memory
==1855==
==1855== For counts of detected and suppressed errors, rerun with: -v
==1855== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Tried with: Valgrind 3.13.0 and Ubuntu 18.04