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 [program]
, where [program]
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 [program]
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.
Callgrind usage
Callgrind is used for profiling your program. To use:
- Compile code with
-g
flag.
- Run
valgrind --tool=callgrind [program]
, where [program]
is what you would normally type to run your program, including all flags and arguments.
- A file should be generated in your current working directory called
callgrind.out.[pid]
, where [pid]
is the pid of the process you just profiled.
- If you have kCacheGrind installed, you should be able to run the file just by double-clicking it, or type in the console:
kcachegrind callgrind.out.[pid]
.
- If everything worked, you should now get a nice GUI view of your program's profile.
- "Incl." is the time the function/method takes to run + the time all the functions it calls takes to run.
- "Self" is the time the function/method takes to run excluding all functions it calls.
- "Called" is the number of times the function was called.