Readablewiki

Memory leak

Content sourced from Wikipedia, licensed under CC BY-SA 3.0.

Memory leak happens when a program uses memory but doesn’t release it when it’s no longer needed. It can also occur when memory is still reserved but the program can’t access it anymore (unreachable). Leaks are hard to spot without looking at the code.

What happens when memory leaks occur
- Leaked memory stays taken, so the program and other apps have less memory to work with.
- Over time, a system may slow down as it starts swapping memory to disk (thrashing).
- If memory runs out, allocations fail and programs can crash.
- Sometimes a leak doesn’t show up right away, especially in short tasks or after restarts.

Why leaks happen
- In languages without automatic memory management (like C or C++), programmers must free memory manually. If they forget, memory leaks.
- Even with garbage collection, leaks can happen if there are cycles of references or if strong references keep objects alive.
- Some systems use caches or intentionally growing data structures, which can look like leaks but aren’t bugs by design.
- If the leak is in the core system (the kernel) or on devices with limited memory, it can cause bigger failures.

How to prevent or fix leaks
- Use RAII (Resource Acquisition Is Initialization) in languages like C++ so resources are released when objects go out of scope.
- In garbage-collected languages, ensure you don’t keep unnecessary references (clear them when done, deregister listeners, etc.).
- Use debugging and profiling tools to find leaks, such as memory checkers and leak detectors.
- Set per-process memory limits to prevent one program from exhausting all memory.
- Fix leaks by explicitly freeing memory, breaking reference cycles, or redesigning parts that grow without bound.

Signs of a memory leak
- Memory usage climbs steadily over time.
- The pattern can look like a sawtooth (memory grows until a restart then drops), but not every rise is a leak (caches can grow on purpose).
- If you don’t have access to code, it’s hard to confirm a leak; you’d need debugging information.

Simple example
- A program keeps allocating memory for a task every time a button is pressed, but never frees it. Each press adds more used memory, until the system runs out.

In short, memory leaks waste RAM, slow systems, and can crash programs. Detecting and fixing them usually requires careful coding practices and the right debugging tools.


This page was last edited on 3 February 2026, at 13:13 (CET).