Valgrind
Valgrind is a dynamic analysis tool, best known for Memcheck: it runs your program on a synthetic CPU and reports invalid reads and writes, use-after-free, double-free, and leaks.
Detailed Explanation
You build with debug symbols (-g) and without ASan (they fight). You run valgrind --leak-check=full ./prog args. Memcheck intercepts malloc and every memory access. A read of uninitialized bytes, a write off the end of a block, a free of a stack address — each becomes a report with a stack trace.
Valgrind is not a compiler sanitizer. It is slower (often 10–50x) and does not need a special build beyond -g. It works on Linux and has limited support elsewhere. macOS support has been spotty; ASan is the usual choice there. Windows is not a target.
Memcheck sees heap blocks clearly. It sees stack and globals less precisely than ASan. It will not catch every stack overflow. It will catch a malloc(n) followed by a write to index n. It reports still-reachable allocations at exit; those may be intentional caches. --leak-check=full --show-leak-kinds=all is the verbose form. --track-origins=yes is slower and tells you where uninitialized bytes came from.
Other Valgrind tools exist: Helgrind and DRD for data races, Callgrind for profiles, Cachegrind for cache misses. They are separate runs. Helgrind understands POSIX locks; it does not understand your homemade spinlock unless you annotate it.
ASan versus Valgrind: ASan is faster, needs a rebuild, catches more stack bugs, and is what CI often runs. Valgrind runs the same binary you shipped (plus -g), which is why it still earns a place when a production-like build misbehaves.
False positives happen with custom allocators, with mmap, and with code that implements its own pools. You can suppress them in a suppressions file. Do not suppress a real invalid write because it is noisy; fix the write.
Code Examples
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int *p = malloc(sizeof *p);
if (p == NULL) {
return 1;
}
*p = 3;
printf("%d\n", *p); /* prints: 3 */
free(p);
return 0;
}
/* Run: valgrind --leak-check=full ./prog
A clean run reports "All heap blocks were freed -- no leaks are possible". */#include <stdlib.h>
int main(void)
{
int *p = malloc(sizeof *p);
if (p == NULL) {
return 1;
}
p[0] = 1;
/* p[1] = 2; would be an invalid write: one int was allocated */
free(p);
return 0;
}Common Gotchas
Do not combine Valgrind Memcheck with `-fsanitize=address`
pick one per run.
Still-reachable blocks at exit are not always bugs
globals and caches appear that way. Decide a policy.
Valgrind is not a substitute for a data-race tool unless you run Helgrind/DRD
Memcheck is about addresses, not about threads missing a lock.
10–50x slowdown changes timing
some race conditions disappear under Valgrind and appear under ASan, or the reverse.