Skip to content

Valgrind Memory Checker

Valgrind is a command line tool for detecting memory errors including - heap bounds access errors, - leaked heap arrays, and - attempting to free previously freed arrays.

It works by intercepting systems calls including memory accesses and doing the type of error handling that we added to the array functions. Unfortunately this might significantly prolong the time it takes to run a program.

Suggestion

Because of the much longer runtime of a program, it is advised to use Valgrind with programs that would normally run very fast.

Compile with debugging

We need to compile a program with the compiler debugging flag -g. This instructs the compiler to include the original source code into the executable.

For example, compile as

gcc -g -o [MY_PROGRAM] [MY_SOURCE].c

Run program with Valgrind

Run with general checks

valgrind [PATH_TO_EXECUTABLE]

Run with additional checks for memory leaks

valgrind --leak-check=full --show-reachable=yes [PATH_TO_EXECUTABLE]

Write Valgrind's output into a log file (not stdout)

valgrind --log-file=[FILENAME] [PATH_TO_EXECUTABLE]


References