How to use valgrind
From ODF::Wiki
This article will help you to learn the basic usage of valgrind. The exact meaning of the error messages can be found in the valgrind errors lesson.
Contents |
[edit] Getting started
[edit] Running valgrind
Easy:
valgrind valgrinds_arguments your_program your_arguments[edit] Why cannot I see the line numbers of where errors/warnings occur?
You need to compile all sources (and hence, if you want to trace line numbers in libraries you are using, also these sources) with g++ -g. This adds debugging symbols into the binary which informs programs like valgrind or gdb about the current line number.
[edit] Understanding an error
The following C program contains a bug:
int main() { int* int_ptr = NULL; *int_ptr = 42; }
Running it, valgrind shows the error among some other output:
==25267== Invalid write of size 4 ==25267== at 0x80483FF: main (valgrind1.c:11) ==25267== Address 0x0 is not stack'd, malloc'd or (recently) free'd
What does mean what?
- ==25267== is the ID of the process. If your program should ever fork() into different processes, you might like to know which process was causing the fault
- Invalid write of size 4 That is the error description. In this case, it is easy to understand: You wrote a value to an address where you were not allowed to. However, valgrind has more complex errors. Some are listed in the valgrind errors lesson.
- at 0x80483FF: main (valgrind1.c:11) - This is the error location
- 0x80483FF - the memory address in the executable where the error occurred. often useless. note: it is a hex number.
- main - function the error occurred in
- (valgrind1.c:3) - file and line number
- Address 0x0 is not stack'd, malloc'd or (recently) free'd - This is a more detailed description. What does it tell us? The error is about the address 0x0, which means NULL. So we have an invalid write to NULL. Yeah, you cannot write to the null pointer. This was easy :)

