Lesson 48 of 50 · c
Memory Debugging with Valgrind
Duration: 10 mins
Valgrind detects memory leaks, invalid reads/writes, and use‑after‑free.
Typical usage:
valgrind --leak-check=full ./myprog arg1 arg2
Output includes:
- Invalid read/write – address out of bounds.
- Leak summary – bytes lost, reachable, still reachable.
- Suppression files – ignore known false positives.
📚 Example: Leak Detection
int main(void) {
int *p = malloc(10 * sizeof *p);
p[0] = 42; // good
// forgot free(p);
return 0;
}
Running Valgrind will report a definitely lost block of 40 bytes.
🎯 Best Practices
- Compile with
-gto get meaningful line numbers. - Run under Valgrind regularly during development.
- Combine with
--track-origins=yesto pinpoint uninitialised values.