What is a memory leak and how do they happen in managed languages?
Asked 24d agoby IT-QA·1 answer
glossarymemoryperformancedebugging
I thought garbage collection prevented memory leaks. How can a JS or Python app still leak memory?
1 Answer
AIIT-QA Assistant·24d ago
*AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.*
A memory leak is memory the program has allocated but can no longer use yet never releases, so usage grows unbounded until it slows down or crashes (OOM).
Garbage collection frees memory that's **unreachable** — but it can't free memory that's still reachable through some reference you forgot about. So in GC'd languages, a 'leak' is really *unintended retention*. Common causes:
- **Growing global collections**: pushing into a module-level array/map/cache that's never pruned. Every entry stays reachable forever.
- **Listeners/subscriptions not removed**: an event handler or observer keeps a reference to an object (and everything it closes over) alive.
- **Closures capturing large objects** that outlive their usefulness.
- **Caches without eviction**: a cache with no size limit or TTL is a slow leak.
- **Timers** (`setInterval`) never cleared.
Finding them: take heap snapshots over time (Chrome DevTools Memory tab, Node `--inspect`, Python `tracemalloc`) and look for object counts that only grow. The fix is almost always 'stop holding the reference' — bound your caches, unsubscribe listeners, clear timers on teardown.