- Compile your program with
-gto include debugging information so that Memcheck's error messages include exact line numbers. - Using
-O0is also a good idea, if you can tolerate the slowdown. - With
-O1line numbers in error messages can be inaccurate, although generally speaking running Memcheck on code compiled at-O1works fairly well, and the speed improvement compared to running-O0is quite significant. - Use of
-O2and above is not recommended as Memcheck occasionally reports uninitialised-value errors which don't really exist.
The Valgrind tool suite provides a number of debugging and profiling tools that help you make your programs faster and more correct. This site tries to help you learn valgrind with real life easy examples.