Tracking Down Memory Leaks in C with Valgrind
The Slow Death of a Service
I once debugged a SIP proxy that would crash exactly every 14 days. It wasn't a logic error; it was a slow, tiny memory leak. Every call leaked 4KB. Over two weeks, that consumed all available RAM, and the OOM (Out of Memory) killer stepped in.
C gives you power, but it demands responsibility. Here is how I use Valgrind to enforce that responsibility.
The Basics of Memcheck
Valgrind is a suite of tools, and Memcheck is the default. Run your program through it like this:
valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes ./my_program
Understanding the Output
Valgrind will produce a report on exit. You are looking for "definitely lost".

In the screenshot above, you can see the exact line number where malloc was called but never free'd. This is the smoking gun.
False Positives and libraries
Sometimes Valgrind reports leaks in libraries like OpenSSL or glibc. These are often "still reachable" memory that the OS reclaims on exit anyway. Focus on YOUR code first. Use suppression files to ignore known library noises.
Performance Warning
Valgrind slows down your application by 20-30x. You cannot run this on a production server taking live traffic. Use a staging environment with traffic generators (like SIPp) to reproduce the leak under monitoring.