Valgrind and sanitizers: Finding memory errors
In short: Tools that detect errors in handling memory while a program runs, such as accesses beyond the end of arrays or forgotten deallocations.
In more detail: In languages such as C and C++ you manage memory yourself. Typical errors: access beyond the end of an array (buffer overflow), use of freed memory (use-after-free), freeing twice (double free), forgetting to free (memory leak) and uninitialised values. They lead to crashes, strange results and security holes, and are hard to find without help.
In Depth
Valgrind (Memcheck)
Valgrind runs the program on a simulated CPU and checks every memory access.
gcc -g -O0 -o prog prog.c
valgrind --leak-check=full ./prog
The output names the kind of error and the source line (hence -g when compiling), for example “Invalid write of size 4 at … by main (prog.c:12)” and “definitely lost: 40 bytes in 1 blocks”. Disadvantage: the program runs 10 to 50 times slower.
AddressSanitizer (ASan)
Compilers such as GCC and Clang build the checks directly into the program:
gcc -g -fsanitize=address -o prog prog.c
./prog
The slowdown is much lower at about a factor of 2, and it finds buffer overflows, use-after-free and leaks (LeakSanitizer). Further sanitizers: UBSan (undefined behaviour such as integer overflow), TSan (race conditions between threads), MSan (uninitialised memory).
Use in everyday work
Run with sanitizers during development and in automated tests before errors show up in production. Together with fuzzing (random inputs) this finds many security holes. Important: the program must also execute the faulty place; the check only finds what is tested.
Other languages
Memory-safe languages such as Rust, Go, Java or Python prevent many of these errors by design (ownership, garbage collector). There, too, tools help, for example profilers for memory leaks through retained references. In Rust the problem is limited to unsafe blocks, which can be checked with Miri.
See also: Memory leak, Stack and heap, Fuzzing, Debuggers and core dumps