Skip to content

This document is a WORK IN PROGRESS.
This is just a quick personal cheat sheet: treat its contents with caution!


Valgrind

Valgrind is an analysis tool suite. It provides a number of debugging and profiling tools that help you make your programs faster and more correct, by detecting automatically many memory management and threading bugs, and by profiling your programs in detail.

Reference(s)
Alternative(s)

Table of contents


Install

# emerge -a dev-util/valgrind
# pacman -S valgrind
# nix-env -iA nixos.valgrind
# nix-env -iA nixpkgs.valgrind
# apt install valgrind
# yum install valgrind
# dnf install valgrind

Config

TODO


Use

TODO

  • First, add the -g compilation option.

    E.g. from gcc -o executable -std=c11 -Wall main.c to gcc -o executable -std=c11 -Wall -g main.c (or e.g. from make to make USR_CFLAGS="-g" USR_CXXFLAGS="-g").

  • Or, add the -ggdb3 compilation option.

    E.g. from gcc -o executable -std=c11 -Wall main.c to gcc -o executable -std=c11 -Wall -ggdb3 main.c (or e.g. from make to make USR_CFLAGS="-ggdb3" USR_CXXFLAGS="-ggdb3").

Then,

$ valgrind --tool=memcheck \
           --leak-check=full \
           --show-leak-kinds=all \
           --track-origins=yes \
           --verbose \
           --log-file=valgrind-out.txt \
           ./executable exampleParam1

The flags are, in short:

  • --tool=memcheck: Use the memory check tool (enable by default, this option is optional).
  • --leak-check=full: "Each individual leak will be shown in detail".
  • --show-leak-kinds=all: Show all of "definite, indirect, possible, reachable" leak kinds in the "full" report.
  • --track-origins=yes: Favor useful output over speed. This tracks the origins of uninitialized values, which could be very useful for memory errors. Consider turning off if Valgrind is unacceptably slow.
  • --verbose: Can tell you about unusual behavior of your program. Repeat for more verbosity.
  • --log-file: Write to a file. Useful when output exceeds terminal space.
alias vg="valgrind --tool=memcheck --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind-out.txt"

with kcachegrind

WIP

$ valgrind --tool=callgrind appname

And run the output through kcachegrind to graphically explore the functions the program uses. If a program hangs, this makes it easier to pinpoint the location of the error.


If this cheat sheet has been useful to you, then please consider leaving a star here.