// Patrick Louis

[C/C++] Valgrind to find memory leaks

Hello readers,

valgrind, from the man page, is a suite of tools for debugging and profiling programs. I’ll introduce you to the memory leak finder feature of valgrind. (note: valgrind only works on posix compliant OS)

First of all install valgrind url It’s the default way of installing any software.

cd to the dir of the program you want to test and run the following:

valgrind --tool=memcheck --leak-check=yes ./the_so_called_program

It will output some infos while the program is running. Once the program has finish its procedure you should take a look at those outputs (normally at the end) and if you see something that ressembles this it means you have memory leaks:

==4156== 8 bytes in 2 blocks are definitely lost in loss record 1 of 4

valgrind will also output infos about invalid pointers, not initialized variables, double free, etc…

Sometimes you might want to have more verbose outputs and running this will be more convenient:

valgrind --tool=memcheck --show-reachable=yes --log-file="logs" --leak-check=yes -v ./the_so_called_program

-v makes it more verbose and “logs” is the logs output that can be analyzed later.

A little end note: when compiling with gcc you should not use stripping flags and should produce debugging symbols so valgrind can help you detect the lines of codes where there are leaks.

You can find more infos about valgrind on the man 1 valgrind.

(PS: you can use gdb later to debug the program if you found where the leak was but are not really sure)




If you want to have a more in depth discussion I'm always available by email or irc. We can discuss and argue about what you like and dislike, about new ideas to consider, opinions, etc..
If you don't feel like "having a discussion" or are intimidated by emails then you can simply say something small in the comment sections below and/or share it with your friends.