Valgrind
is a software suite that includes many useful tools, like a memory checker and a cache profiler.
Installation
I'm not really sure how to install this on Windows. I've only installed this on my own machine running Ubuntu 9.10. To install, just open a terminal and type:
-
sudo apt-get install valgrind
and it should do the rest.
I also find
KCacheGrind
to be a very useful tool for visualizing the output of Callgrind. Installation instructions can be found
here
, but I also just used apt-get:
-
sudo apt-get install kcachegrind
.
Memcheck usage
Memcheck is used for checking for memory leaks and memory errors, and is also useful for debugging segmentation faults. Basic usage of memcheck is:
- Compile your code with
-g -O0
flags. -g
enables debugging mode and allows memcheck to display line numbers. -O0
compiles with no optimizations; higher levels can be used, but you might get false positives. Memcheck recommends using less than level O2.
- Note: compiling with these flags can be done by setting the
CMAKE_CXX_FLAGS
and CMAKE_C_FLAGS
variables in the main CMakeLists.txt
file. Better yet, set a CMAKE_CXX_FLAGS_DEBUG
and CMAKE_C_FLAGS_DEBUG
and configure using ccmake
to use compile a Debug version.
- Run
valgrind
, where
is what you would normally type to run your program, including all flags and arguments. This will give you a summary of memory leaks and basic memory errors.
- If you get memory leaks, try running
valgrind --leak-check=full
to see exactly where leaks are happening. I believe this will make your program run a lot slower, so you may have to sit around and wait for a while. If it's too slow, try compiling with a higher optimization level.
Here
's a nice overview of memcheck in general. Section 4.2 will give you a basic description of all the error messages, while section 4.3 will give you more command line options.