CSE Roadmap

Core tier · about 5 hours · 7 parts

Part 5 of 7 · 2 min read

Valgrind

In plain words: Valgrind takes the opposite approach. The program is not rebuilt. Valgrind's Memcheck tool runs the ordinary binary on a simulated processor, and it watches every instruction. It keeps a record of which bytes are allocated and which bytes hold a defined value, so it can find the case that ASan missed: a decision made on an uninitialised value.

gcc -g -O0 -o bugs bugs.c
valgrind --leak-check=full ./bugs 2

The reports for the cases of section 1:

Case Valgrind message
1, overflow "Invalid write of size 1 ... 0 bytes after a block of size 16 alloc'd", at bugs.c:9
2, use after free "Invalid read of size 1 ... 0 bytes inside a block of size 16 free'd", with the stacks of the free and of the allocation
4, leak "16 bytes in 1 blocks are definitely lost" with the allocating line
5, uninitialised "Conditional jump or move depends on uninitialised value(s)" at bugs.c:13

The cost is large. The same summing loop took 0.889 s under Valgrind against 0.024 s plain, about 37 times longer. On the other hand, no recompilation is needed, and the uninitialised-value check is something ASan does not offer. The two tools suit different jobs: ASan for everyday test runs, which is fast enough to run the whole test suite, and Valgrind for a deep check, for a binary that cannot be rebuilt, or for uninitialised reads. The two cannot be used in the same run.

Memcheck

Memcheck is the default tool of Valgrind. It runs an unchanged program on a simulated processor, records which bytes are allocated and which are defined, and reports invalid accesses, uses of undefined values and leaks.

Example: a branch that depends on an int that was never assigned makes Memcheck print "Conditional jump or move depends on uninitialised value(s)".

Interview angle

"How do you debug memory corruption in C?" A good answer says to compile with -fsanitize=address and -g, run the failing test, and read the report for the first illegal access and the stacks of the allocation and the free. It adds Valgrind for uninitialised reads, and a note that both slow the program down.

Check yourself: 1. Why can Valgrind find the uninitialised read that ASan did not? 2. What does Valgrind cost in time, according to the measurement above? 3. When is Valgrind a better choice than ASan?