Valgrind
Super useful for debugging in C and C++. Especially for finding memory allocation errors. (Memory leaks the fear of my life.)
Valgrind’s primary use is as a memory checking tool. First learned how to use in CS137. It provides a virtual CPU that it executes your program on - checks for memory access, etc.
Typically programs executed through valgrind are 3-4x slower than usual (don’t use it for performance monitoring).
Important
USE
-g
flag when compiling in order to use valgrind or gdb. (I’ve had issues when setting up the debugger on the student server, forgetting to include-g
…)
Other important information:
- Using
--leak-check=full
allows you to see where leaked memory was allocated - Valgrind can only inform on memory leaks for one particular invocation of the program
- Highlights the importance of designing various test cases that hit each part of the program.
Detection of invalid cases
Can also detect invalid reads: report the line of your source code where the invalid read happened.
Invalid write - we get 3 pieces of info:
- where the invalid write occurred
- where the memory was freed
- where the memory was initially allocated
Can also detect invalid uses of delete
/ delete[]
.
[
Valgrind output might be for an adjacent GTest test case
The output of Valgrind does not necessarily interleave with the GTest output in the way you are expecting.
Valgrind output goes to stderr. GTest output goes to stdout.
./valgrind --leak-check=full -s yourBinaryFileName < test.in
These messages can appear on the console out of order.
Consider the following output below:
- It looks like Valgrind is reporting an error in IsWellformedNode.GivenSelfCycleNodeInPrevInvokedIsWellformedNodeExpectedFalseAssertion
- But the issue is actually in IsWellformedNode.GivenSelfCycleNodeInNextInvokedIsWellformedNodeExpectedFalseAssertion
- Messages to stdout and messages to stderr might arrive on the console out of order.
- This is called a race condition: stdout and stderr are in a race to the console.
- When you are fixing valgrind errors, be aware that they might come from an adjacent test case
This is part of the real world that we usually try to protect first year students from. As we try to work in more professional ways with more professional tools, we experience some of these things. These are real things that you need to learn eventually.