Memory Leak Debugger
Prerequisites & Dependencies
- Node.js with
--inspect/ Chrome DevTools, or Pythontracemalloc, or Gogo tool pprof - Access to heap snapshots or memory profiling tools
- Basic understanding of GC roots and reference cycles
Execution Steps
- Start the application with memory profiling enabled (
node --inspect,python -m tracemalloc,go pprof http://localhost:6060) - Exercise the app until the leak becomes noticeable (growing heap size, OOM warnings)
- Take a heap snapshot and compare it over time (
heap-diff,tracemalloc.compare_to,pprof web) - Identify retaining objects: look for large arrays, closures, DOM/event listeners, or unresolved Promises
- Remove unexpected references: clear timers/intervals, remove event listeners (
removeEventListener), useWeakMap/weakrefwhere appropriate - Re-run the profile to confirm the leak is sealed, and add automated memory regression tests
# Python example: detecting leaks with tracemalloc
import tracemalloc
tracemalloc.start()
def allocate_leak():
# simulate unbounded growth
data = [] * 10000 # grows each call
return data
# Run and snapshot
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.compare_to(tracemalloc.take_snapshot(), 'lineno')
for stat in top_stats[:5]:
print(stat)