Xavier Lamorlette

Valgrind

Notes sur Valgrind, issuees d'une formation de Julian Seward, et de mon expérience.

Le site de Valgrind est valgrind.org.

Saint George and the Dragon - Valgrind

Sommaire :

Memcheck

Memcheck (+ Valkyrie UI): memory error detector:

Recommended compiling options:

Run Memcheck:

valgrind --tool=memcheck --xml=yes --leak-check=full --show-reachable=yes --xml-file=results.xml program [with its arguments]

Options:

Make requests from code:

#include <memcheck/memcheck.h>

Callgrind

Callgrind (+ KCachegrind UI): low level time profiler and function-call profiler, simulating CPU caches.

Recommended compiling options:

Run Callgrind:

valgrind --tool=callgrind --simulate-cache=yes --branch-sim=yes --cacheuse=yes \
--callgrind-out-file=callgrind.out program [with its arguments]
callgrind_annotate callgrind.out [source files to annotate] | grep -v callgrind_annotate

Manual selective profiling:

Automatic selective profiling:

valgrind --tool=callgrind --simulate-cache=yes \
--toggle-collect="*MyClass::MyMethod*" \
--dump-after="MyClass::MyMethod(arguments)" \
program [with its arguments]
To get the exact signature of a function:
nm -l -C libdll.so | grep MyMethod

One file per thread: --separate-threads=yes.

Cachegrind

Cachegrind: simpler than Callgrind. Does branch predictions.

Run Cachegrind:

valgrind --tool=cachegrind --branch-sim=yes --cache-sim=yes program [with its arguments]
cg_annotate cachegrind.out.[pid] [source files to annotate]  # or --auto=yes

Other other profiling tools

Massif

Massif: heap memory space profiler. Takes periodic snapshots of heap.

Run Massif:

valgrind --tool=massif program [with its arguments]

Display Massif data:

ms_print massif.out.valgrind.[pid]

ms_print options:

Tool similar to Massif: DHAT.

Helgrind

Helgrind: thread error detector.

Similar tool: DRD.

Track Memory Leaks with crtdbg.h on MSVC

Source: "Rust Devs Think We’re Hopeless; Let’s Prove Them Wrong (with C++ Memory Leaks)!" by Mamadou Babei (May 2025).

#define MEMORY_LEAK_TRACKER 1

#if MEMORY_LEAK_TRACKER
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>

#define DEBUG_NEW new (_NORMAL_BLOCK, __FILE__, __LINE__)
#define new DEBUG_NEW
#endif  /* MEMORY_LEAK_TRACKER */

[…]

#if MEMORY_LEAK_TRACKER
    int dbgFlags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
    dbgFlags |= _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF;
    _CrtSetDbgFlag(dbgFlags);

    // Only track one allocation per run!
    // e.g. allocation number that causes leaks:
    //_CrtSetBreakAlloc(162);
#endif  /* MEMORY_LEAK_TRACKER */

La dernière mise à jour de cette page date de juin 2025.

Le contenu de ce site est, en tant qu'œuvre originale de l'esprit, protégé par le droit d'auteur.
Pour tout commentaire, vous pouvez m'écrire à xavier.lamorlette@gmail.com.