Skip to content

How to Find Memory Leaks

This short guide covers two fast and effective ways to find memory leaks:

This short guide covers two fast and effective ways to find memory leaks: (1) using pidstat to monitor memory growth, and (2) using gdb to trace memory allocations by setting a breakpoint in malloc.

1. Using pidstat to Monitor Memory Growth

pidstat is a simple way to check if your program’s memory usage keeps increasing over time — a common sign of a memory leak.

Example:

pidstat -r -p 187610 5 100

Where:

-r shows memory statistics.

-p 187610 tracks process ID 187610.

5 100 means sample every 5 seconds, 100 times.

If the VSZ (virtual memory size) or RSS (resident set size) grows steadily without stabilizing, it suggests a memory leak.

Example output:

Linux 5.10.0-8-amd64 (hostname)     04/25/25    _x86_64_    (4 CPU)

#      Time   UID   PID  minflt/s  majflt/s     VSZ    RSS   %MEM
04:00:00   1000 187610    15.00     0.00  123456  23456   0.5
04:00:05   1000 187610    20.00     0.00  123660  23600   0.6
04:00:10   1000 187610    25.00     0.00  123860  23800   0.6
...

Notice the VSZ and RSS steadily increase: potential leak.

2. Using gdb to Trace malloc Calls

Sometimes, valgrind is too slow for large or real-time programs. A faster trick is to use gdb to log all memory allocations directly.

Note

In high-performance programming, there should not be any malloc calls once the program is initialized and actively working.

Steps:

Attach gdb to your process:

gdb -p 187610

In gdb, set a breakpoint on __libc_malloc and save output to a file:

b __libc_malloc
commands
  set logging on
  set pagination off
  bt
  cont
end

Explanation:

  • b __libc_malloc sets a breakpoint on every malloc.
  • commands block automatically:

    • set logging on writes output to gdb.txt.
    • set pagination off avoids pauses.
    • bt (backtrace) shows where each malloc happened.
    • cont continues running without manual intervention.

Once your program runs for a enough time to catch some mallocs, you can review gdb.txt to find where most memory allocations happen — and spot potential leaks.

Conclusion

Use pidstat first: fast and non-invasive.

Use gdb malloc tracing when you need to quickly catch frequent allocation points without the heavy overhead of tools like valgrind.