Conceptcore
Memory leak
Also called leak, memory leakage, CWE-401.
A memory leak is memory that a program keeps after it can no longer use it. The memory comes back only when the process exits, so a long-running program grows until it slows down or fails.
- Applies to
- core-languages
Idea
A program asks for memory, uses it, and must give it back when it is done. A memory leak is memory that the program never gives back after its last use. CWE lists the weakness as CWE-401, Missing Release of Memory after Effective Lifetime.1 A short program that leaks a little is harmless, because the operating system takes all the memory back at exit. A server that leaks a little on each request grows until it slows down or fails.
There are two kinds of leak. In C and C++, the program frees each block by hand. A block leaks when the program loses its last pointer to the block, so no code can free it. A collector frees unreachable objects, so this kind cannot happen in Python, Java or Go. There, an object leaks when the program can still reach it but never uses it again. A cache that only grows is the usual case.
import weakref
class Report:
def __init__(self, title):
self.title = title
self.rows = [0] * 100_000
_cache = {}
def load(title):
report = Report(title)
_cache[title] = report # the cache keeps a reference
return report
report = load("q3")
probe = weakref.ref(report)
del report
print("alive after del:", probe() is not None)
print("cache entries:", len(_cache))
_cache.pop("q3")
print("alive after pop:", probe() is not None)
alive after del: True
cache entries: 1
alive after pop: False
The weak reference shows whether the object still exists, without keeping it alive.16 After del report, the program has no name for the report, but _cache still refers to it. The memory comes back only when the cache entry goes.
How it works
A leak checker and a collector both start at the roots: global variables, thread stacks, CPU registers and thread-local storage. They follow each pointer from the roots to the blocks it reaches, and then the pointers in those blocks. The diagram shows the three groups that this walk finds.
roots heap
stack main -----> Session ----> Buffer live: the program uses it
global cache -----> Entry ----> Report reachable, never used again
Block A ----> Block B unreachable, never freed
A collector frees Block A and Block B, because no path from a root reaches them. In C, nothing frees them, so they leak. The middle row leaks in every language. No tool can tell that the program will never read Report again, because that depends on what the program does in the future.
Valgrind Memcheck uses four names for these blocks. Block A is "definitely lost": no pointer to it remains. Block B is "indirectly lost": only a lost block points to it. A block that only an interior pointer reaches is "possibly lost". The middle row is "still reachable". By default, Memcheck lists neither indirectly lost nor still reachable blocks one by one. A fix for the definitely lost block also removes the indirect leak.3 LeakSanitizer reports Block A as a direct leak and Block B as an indirect leak.7
LeakSanitizer does its work when the process exits. It stops the process and scans the roots for words that look like pointers into the heap. A pointer into the middle of a block counts.7
procedure check_leaks_at_exit()stop all threadsmarked <- empty setfor each word w in the globals, stacks, registers and thread-local storagemark(the heap block that w points into)for each allocated block bif b is not in markedreport b with the stack trace of its allocationprocedure mark(b)if b is a block and b is not in markedadd b to markedfor each word w in bmark(the heap block that w points into)
The report gives the stack trace of each leaked allocation. It does not show where the program lost the last pointer. Memcheck has the same limit.3
A collected language needs a different method. The leaked objects are reachable, so no scan at exit can find them. Instead, take two heap snapshots, one before and one after a repeated action, and compare them. Object counts that grow show what leaks. The path from a root to one of those objects shows what keeps it alive. Chrome DevTools calls this path the retainers, and the .NET command gcroot prints it.2730
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Standard library | |
| Java | Native | |
| C | Absent | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | On the JVM the collector frees objects that no live thread can reach, but a companion object map or a listener that is never removed still keeps its objects; no example file because kotlinc is not installed on the machine that recorded the examples. Alternative: A bounded LinkedHashMap, a WeakHashMap, or a coroutine scope that cancels its child coroutines. |
| SQL | Does not apply | The database engine manages its memory, and a query has no pointers or object references. |
| Bash | Does not apply | The shell manages its own strings and arrays, and a script has no heap objects or pointers. Alternative: In a long-running loop, unset arrays that only grow. |
| PowerShell | Native | The .NET collector frees unreachable objects, but a script-scope collection or an event subscription from Register-ObjectEvent keeps its objects; no example file because pwsh is not installed on the machine that recorded the examples. Alternative: Remove the subscription with Unregister-Event and clear long-lived collections at a known point. |
| HTML | Does not apply | Markup has no memory that the program allocates; DOM leaks belong to the JavaScript engine. |
| CSS | Does not apply | Style rules have no memory that the program allocates. |
| Regular expressions | Does not apply | A pattern has no memory that the program allocates. |
| Language | Verdict | How leaks happen and how to find them |
|---|---|---|
| Python | native | reference counting and a cycle collector free unreachable objects; reachable caches leak; tracemalloc compares snapshots14 |
| JavaScript | native | the engine collects unreachable objects; listeners and closures that stay registered leak; heap snapshots in DevTools27 |
| TypeScript | native | the collector of the JavaScript engine that runs the output; the same tools apply |
| Java | native | the collector frees objects that no live thread can reach; static maps leak; heap dumps and JFR1718 |
| C# | native | the .NET collector; an event keeps each subscriber alive; dotnet-gcdump and dotnet-dump282930 |
| Go | native | the collector frees memory, but a blocked goroutine keeps its stack; runtime.NumGoroutine and pprof profiles3234 |
| Kotlin | native | the JVM collector on Kotlin/JVM, with the same leaks as Java |
| PowerShell | native | the .NET collector, as for C# |
| Rust | native | ownership frees each value at the end of its scope; a leak is safe, so Box::leak and mem::forget need no unsafe3940 |
| C++ | stdlib | std::unique_ptr and other owners free on each exit path; a raw new leaks on a skipped delete; LeakSanitizer136 |
| C | absent | malloc and free by hand; LeakSanitizer and Valgrind find lost blocks63 |
| Bash | n/a | the shell manages its own strings and arrays; a script has no pointers |
| SQL | n/a | the database engine manages its memory; a query has no pointers |
| Regex | n/a | a pattern does not allocate memory itself |
| HTML/CSS | n/a | markup and style do not allocate memory; DOM leaks belong to the JavaScript engine |
Manual memory. In C, each malloc needs exactly one free on each path. Leaks come from a few patterns. An assignment overwrites the last pointer to a block. An early return on an error path skips the free. A call p = realloc(p, n) loses the old block when it fails, because a failed realloc returns a null pointer and keeps the old block.11 C++ adds exceptions. Stack unwinding destroys the local objects of each frame it leaves, but a raw pointer is not an owner, so its target stays.12 std::unique_ptr deletes its object when the owner goes out of scope, and that includes unwinding.13 See Resource acquisition is initialization for the general rule and Manual memory management for the allocator side.
Collected languages. Python, JavaScript, Java, C# and Go free objects that the program cannot reach. What leaks is a reference that the program forgot. It is usually in a global or static collection or in a listener list on a long-lived object. It can also be a captured variable of a closure, or the stack of a thread or goroutine that never ends. The Java specification defines a reachable object as one that any potential continuing computation from any live thread can access.17 So a thread that never ends keeps alive all that its stack refers to. A Java leak ends in an OutOfMemoryError with the detail "Java heap space".18
Ownership. Rust frees each value when its owner goes out of scope. The language does not promise that destructors run. A cycle of Rc values, a call to mem::forget, or process::exit skips them, and none of these is unsafe.3941 Box::leak turns a box into a reference that lives for the rest of the program. It suits data that the program needs until it exits.40
Tools. In C and C++, build tests with -fsanitize=address. AddressSanitizer includes LeakSanitizer and enables it by default on Linux; on macOS, set ASAN_OPTIONS=detect_leaks=1.8 -fsanitize=leak gives LeakSanitizer alone, and a suppression file can hide known leaks in third-party code.6 Valgrind needs no rebuild: valgrind --leak-check=full ./prog gives details for each lost block.34 In Python, tracemalloc takes snapshots and Snapshot.compare_to gives the difference by file or line.14 In Go, the heap profile of runtime/pprof shows the allocation sites of live objects as of the last collection.34 In Java, jcmd <pid> GC.heap_dump writes a heap dump. The Old Object Sample event of Flight Recorder records the path to a GC root for sampled objects.18 In Node.js, --heapsnapshot-signal and v8.writeHeapSnapshot() write snapshots for Chrome DevTools.2526 In .NET, dotnet-gcdump collects a heap graph and dotnet-dump with the SOS commands dumpheap -stat and gcroot analyzes a full dump.2930
import tracemalloc
import weakref
class Image:
def __init__(self, name):
self.name = name
self.pixels = bytearray(10_000)
def growth(cache, count):
"""Loads count images through cache and returns the traced growth in bytes."""
before = tracemalloc.take_snapshot()
for i in range(count):
image = Image(f"img-{i}")
cache[image.name] = image
after = tracemalloc.take_snapshot()
return sum(stat.size_diff for stat in after.compare_to(before, "filename"))
tracemalloc.start()
strong = {}
print("strong cache grew over 500 KB:", growth(strong, 100) > 500_000)
print("strong cache size:", len(strong))
weak = weakref.WeakValueDictionary()
print("weak cache grew over 500 KB:", growth(weak, 100) > 500_000)
print("weak cache size:", len(weak))
kept = Image("logo")
weak[kept.name] = kept
print("weak cache size with one image in use:", len(weak))
tracemalloc.stop()
strong cache grew over 500 KB: True
strong cache size: 100
weak cache grew over 500 KB: False
weak cache size: 0
weak cache size with one image in use: 1
- Verdict: native. CPython frees an object when its last reference goes. A plain
dictused as a cache is a reference, so its values stay reachable after the program stops using them. tracemalloccompares two snapshots. Growth that stays after the work is done points to the leak;compare_togroups the difference by file or by line.WeakValueDictionarydrops an entry when no other code refers to the value. For a cache that must keep values, usefunctools.lru_cachewith amaxsize.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <print>
#include <stdexcept>
#include <string>
struct Order {
std::string id;
int quantity;
};
int checked_quantity(const Order& order) {
if (order.quantity <= 0) {
throw std::invalid_argument("bad quantity in " + order.id);
}
return order.quantity;
}
int process(int quantity) {
Order* order = new Order{"A-1", quantity};
int result = checked_quantity(*order); // a throw skips the delete below
delete order;
return result;
}
int main() {
std::println("processed: {}", process(3));
try {
process(0);
} catch (const std::invalid_argument& e) {
std::println("error: {}", e.what());
}
}
The program prints the error and exits normally. LeakSanitizer then reports the Order from the second call. Stack unwinding destroys local objects, but order is a raw pointer, and destroying a pointer does not delete its target.
#include <memory>
#include <print>
#include <stdexcept>
#include <string>
struct Order {
std::string id;
int quantity;
~Order() { std::println("order {} deleted", id); }
};
int checked_quantity(const Order& order) {
if (order.quantity <= 0) {
throw std::invalid_argument("bad quantity in " + order.id);
}
return order.quantity;
}
int process(int quantity) {
auto order = std::make_unique<Order>("A-1", quantity);
return checked_quantity(*order); // unwinding destroys order, which deletes the Order
}
int main() {
std::println("processed: {}", process(3));
try {
process(0);
} catch (const std::invalid_argument& e) {
std::println("error: {}", e.what());
}
}
order A-1 deleted
processed: 3
order A-1 deleted
error: bad quantity in A-1
- Verdict: stdlib.
std::unique_ptrowns the object. Its destructor runs on a return and on stack unwinding, so each path deletes theOrder. - The output shows
order A-1 deletedbeforeerror:. The destructor runs while the exception leavesprocess, before the handler inmainstarts. - A raw
newwith a laterdeleteleaks on each path that skips thedelete: an earlyreturn, athrow, or abreak.
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.WeakHashMap;
public class Main {
record Session(String user) {}
// Leaks: a static map is reachable for the life of the class.
static final Map<Integer, byte[]> RESULTS = new HashMap<>();
// Fixed: a map in access order that drops the eldest entry above max.
static final class Lru<K, V> extends LinkedHashMap<K, V> {
private final int max;
Lru(int max) {
super(16, 0.75f, true);
this.max = max;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > max;
}
}
static final Map<Integer, byte[]> BOUNDED = new Lru<>(100);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 1000; i++) {
RESULTS.put(i, new byte[1024]);
BOUNDED.put(i, new byte[1024]);
}
System.out.println("static HashMap size: " + RESULTS.size());
System.out.println("bounded LinkedHashMap size: " + BOUNDED.size());
// Fixed: a WeakHashMap entry goes when its key is no longer in use.
Map<Session, byte[]> perSession = new WeakHashMap<>();
Session kept = new Session("kept");
perSession.put(kept, new byte[1024]);
for (int i = 0; i < 100; i++) {
perSession.put(new Session("user-" + i), new byte[1024]);
}
long deadline = System.nanoTime() + 5_000_000_000L;
while (perSession.size() > 1 && System.nanoTime() < deadline) {
System.gc();
Thread.sleep(10);
}
System.out.println("WeakHashMap size after gc: " + perSession.size());
System.out.println("kept key still present: " + perSession.containsKey(kept));
}
}
static HashMap size: 1000
bounded LinkedHashMap size: 100
WeakHashMap size after gc: 1
kept key still present: true
- Verdict: native. The collector frees objects that no live thread can reach. A
staticfield is reachable while its class is loaded, so a static map keeps each entry it holds. LinkedHashMapcallsremoveEldestEntryafter eachput. Thetrueconstructor argument selects access order, so the map drops the entry that the program used longest ago.WeakHashMapholds its keys weakly and its values strongly. A value that refers to one of the keys keeps that entry alive.- The loop calls
System.gc()until the map has one entry or 5 seconds pass, because a collection can run later than the call.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Returns a copy of the longest line. The caller frees it.
char *longest(const char *lines[], size_t count) {
char *best = NULL;
for (size_t i = 0; i < count; i++) {
if (best == NULL || strlen(lines[i]) > strlen(best)) {
best = malloc(strlen(lines[i]) + 1); // the old block loses its last pointer
if (best == NULL) {
return NULL;
}
strcpy(best, lines[i]);
}
}
return best;
}
int main(void) {
const char *lines[] = {"red", "green", "yellow"};
char *best = longest(lines, 3);
if (best == NULL) {
return 1;
}
printf("longest: %s\n", best);
free(best);
}
LeakSanitizer reports two direct leaks at exit, the copies of red and green. Each malloc overwrites best, so no pointer to the old block remains and no code can free it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Returns a copy of the longest line. The caller frees it.
char *longest(const char *lines[], size_t count) {
char *best = NULL;
for (size_t i = 0; i < count; i++) {
size_t len = strlen(lines[i]);
if (best == NULL || len > strlen(best)) {
// A failed realloc keeps the old block, so keep its pointer too.
char *bigger = realloc(best, len + 1);
if (bigger == NULL) {
free(best);
return NULL;
}
best = bigger;
memcpy(best, lines[i], len + 1);
}
}
return best;
}
int main(void) {
const char *lines[] = {"red", "green", "yellow"};
char *best = longest(lines, 3);
if (best == NULL) {
return 1;
}
printf("longest: %s\n", best);
free(best);
}
longest: yellow
- Verdict: absent. C has no owner for a heap block. A block leaks when the program overwrites or drops the last pointer to it before
free. - The fix keeps one block and grows it with
realloc. The result goes into a temporary, becausebest = realloc(best, n)loses the old block whenreallocfails. - Build tests with
-fsanitize=address. LeakSanitizer then lists each leaked block with the stack of itsmallocwhen the process exits.
using System.Runtime.CompilerServices;
var clock = new Clock(); // lives as long as the program
WeakReference leaked = Subscribe(clock, unsubscribe: false);
WeakReference removed = Subscribe(clock, unsubscribe: true);
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Console.WriteLine($"subscriber without -= still alive: {leaked.IsAlive}");
Console.WriteLine($"subscriber with -= collected: {!removed.IsAlive}");
Console.WriteLine($"handlers left on the clock: {clock.HandlerCount}");
GC.KeepAlive(clock);
// NoInlining keeps the subscriber in a frame that is gone before GC.Collect runs.
[MethodImpl(MethodImplOptions.NoInlining)]
static WeakReference Subscribe(Clock clock, bool unsubscribe)
{
var view = new View();
clock.Tick += view.OnTick;
if (unsubscribe)
{
clock.Tick -= view.OnTick;
}
return new WeakReference(view);
}
class Clock
{
public event EventHandler? Tick;
public int HandlerCount => Tick?.GetInvocationList().Length ?? 0;
}
class View
{
private readonly byte[] buffer = new byte[10_000];
public void OnTick(object? sender, EventArgs e) => buffer[0]++;
}
subscriber without -= still alive: True
subscriber with -= collected: True
handlers left on the clock: 1
- Verdict: native. The .NET collector frees objects that no root can reach. An event holds a delegate, and the delegate holds the object of its method, so the publisher keeps each subscriber alive.
- Only the subscriber that ran
-=is collected. The other one lives as long asclockdoes. - In a dump,
dotnet-gcdumpor the SOS commandgcrootshows the path from a root through the event to the subscriber.
const page = new EventTarget(); // lives as long as the program
let resizeCalls = 0;
class Widget {
constructor(name) {
this.name = name;
this.buffer = new Array(10_000).fill(0);
}
onResize() {
resizeCalls += 1;
}
}
// Counts the listeners by sending one event to them.
function countListeners() {
resizeCalls = 0;
page.dispatchEvent(new Event("resize"));
return resizeCalls;
}
// Leaks: page keeps the listener, and the listener keeps the widget.
function mountLeaky(name) {
const widget = new Widget(name);
page.addEventListener("resize", () => widget.onResize());
return new WeakRef(widget);
}
// Fixed: aborting the signal removes the listener.
function mountWithSignal(name, signal) {
const widget = new Widget(name);
page.addEventListener("resize", () => widget.onResize(), { signal });
return new WeakRef(widget);
}
async function collect() {
// A WeakRef target stays alive until the current job ends.
await new Promise((resolve) => setTimeout(resolve, 0));
globalThis.gc();
}
async function main() {
const leaky = [];
for (let i = 0; i < 5; i++) leaky.push(mountLeaky(`w${i}`));
await collect();
console.log("listeners on page:", countListeners());
console.log("leaky widgets alive:", leaky.filter((r) => r.deref()).length);
const controller = new AbortController();
const fixed = [];
for (let i = 0; i < 5; i++) fixed.push(mountWithSignal(`f${i}`, controller.signal));
console.log("listeners on page:", countListeners());
controller.abort();
await collect();
console.log("listeners on page after abort:", countListeners());
console.log("fixed widgets alive:", fixed.filter((r) => r.deref()).length);
// WeakMap: data for each object that does not keep the object alive.
const sizes = new WeakMap();
let widget = new Widget("w-map");
const probe = new WeakRef(widget);
sizes.set(widget, { width: 640 });
widget = null;
await collect();
console.log("WeakMap key collected:", probe.deref() === undefined);
}
main();
listeners on page: 5
leaky widgets alive: 5
listeners on page: 10
listeners on page after abort: 5
fixed widgets alive: 0
WeakMap key collected: true
- Verdict: native. The engine collects unreachable objects. A listener on a long-lived target is reachable, and so is each object that its closure captures.
countListenerssends one event and counts the calls, so the output does not depend on an engine API.- The
signaloption removes all the listeners of a component with oneabort()call.removeEventListenerworks too, but it needs the same function object thataddEventListenergot. - In a heap snapshot, the retainers of a leaked widget show the path from
pagethrough the listener.
type Listener<T> = (value: T) => void;
class Emitter<T> {
#listeners = new Set<Listener<T>>();
// Returns a function that removes the listener.
on(listener: Listener<T>, signal?: AbortSignal): () => void {
this.#listeners.add(listener);
const off = () => {
this.#listeners.delete(listener);
};
signal?.addEventListener("abort", off, { once: true });
return off;
}
emit(value: T): void {
for (const listener of this.#listeners) listener(value);
}
get size(): number {
return this.#listeners.size;
}
}
class Session {
readonly user: string;
seen: number[] = [];
constructor(user: string) {
this.user = user;
}
}
const prices = new Emitter<number>(); // lives as long as the program
// Leaks: no session removes its listener.
for (let i = 0; i < 100; i++) {
const session = new Session(`user-${i}`);
prices.on((price) => session.seen.push(price));
}
console.log("listeners after 100 leaky sessions:", prices.size);
// Fixed: each session calls the function that on() returned.
const fixed = new Emitter<number>();
for (let i = 0; i < 100; i++) {
const session = new Session(`user-${i}`);
const off = fixed.on((price) => session.seen.push(price));
off();
}
console.log("listeners after unsubscribe:", fixed.size);
// Fixed: one AbortController ends a group of sessions.
const withSignal = new Emitter<number>();
const controller = new AbortController();
for (let i = 0; i < 100; i++) {
const session = new Session(`user-${i}`);
withSignal.on((price) => session.seen.push(price), controller.signal);
}
console.log("listeners before abort:", withSignal.size);
controller.abort();
console.log("listeners after abort:", withSignal.size);
listeners after 100 leaky sessions: 100
listeners after unsubscribe: 0
listeners before abort: 100
listeners after abort: 0
- Verdict: native. TypeScript runs on the JavaScript engine and its collector. The types do not show which object keeps a listener.
onreturns its ownofffunction, so the caller does not need to keep the listener to remove it.- An
AbortSignalremoves a group of listeners at one point, for example when a page or a request ends.
package main
import (
"context"
"fmt"
"runtime"
"time"
)
// Leaks: only the first send has a receiver. The other workers block forever.
func firstLeaky(n int) int {
results := make(chan int)
for i := range n {
go func() { results <- i * i }()
}
return <-results
}
// Fixed: the deferred cancel ends the workers that lost the race.
func firstWithContext(n int) int {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
results := make(chan int)
for i := range n {
go func() {
select {
case results <- i * i:
case <-ctx.Done():
}
}()
}
return <-results
}
// waitFor polls until want goroutines exist or the deadline passes.
func waitFor(want int) int {
deadline := time.Now().Add(5 * time.Second)
for runtime.NumGoroutine() != want && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
return runtime.NumGoroutine()
}
func main() {
base := runtime.NumGoroutine()
firstLeaky(10)
fmt.Println("leaked goroutines:", waitFor(base+9)-base)
before := runtime.NumGoroutine()
firstWithContext(10)
fmt.Println("leaked goroutines with context:", waitFor(before)-before)
}
leaked goroutines: 9
leaked goroutines with context: 0
- Verdict: native. The collector frees unreachable memory, but it does not stop a goroutine. A blocked goroutine keeps its stack and each value that the stack refers to.
firstLeakyreturns after one receive. Nine workers then wait to send on a channel that no code reads.waitForpolls with a deadline, because the workers start and stop on the schedule of the runtime.- In a running service, the
goroutineprofile ofnet/http/pprofgroups goroutines by stack. A count that grows at one stack points to a leak.
use std::collections::VecDeque;
use std::mem;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
static DROPS: AtomicUsize = AtomicUsize::new(0);
struct Tracked;
impl Drop for Tracked {
fn drop(&mut self) {
DROPS.fetch_add(1, Ordering::SeqCst);
}
}
// Leaks: a static Vec is reachable until the process ends.
static HISTORY: Mutex<Vec<String>> = Mutex::new(Vec::new());
// Fixed: a static queue that drops the oldest entry above 100.
static RECENT: Mutex<VecDeque<String>> = Mutex::new(VecDeque::new());
fn record(line: String) {
HISTORY.lock().unwrap().push(line.clone());
let mut recent = RECENT.lock().unwrap();
if recent.len() == 100 {
recent.pop_front();
}
recent.push_back(line);
}
fn main() {
// Box::leak is safe: the String lives for the rest of the program.
let config: &'static mut String = Box::leak(Box::new(String::from("mode=fast")));
config.push_str(",retries=3");
println!("leaked config: {config}");
// mem::forget is safe too: the destructor never runs.
drop(Tracked);
mem::forget(Tracked);
println!("drops run: {}", DROPS.load(Ordering::SeqCst));
for i in 0..1000 {
record(format!("request {i}"));
}
println!("history entries: {}", HISTORY.lock().unwrap().len());
println!("recent entries: {}", RECENT.lock().unwrap().len());
}
leaked config: mode=fast,retries=3
drops run: 1
history entries: 1000
recent entries: 100
- Verdict: native. Ownership frees each value when its owner goes out of scope. Rust does not count a leak as a memory safety error, so
Box::leakandmem::forgetare safe functions. - Two
Trackedvalues exist, but only one destructor runs, becausemem::forgettakes the other one without dropping it. - A
staticcollection has no owner that goes out of scope. Give it a limit, asRECENTdoes, or clear it at a known point.
Variations and related ideas
- Weak references and weak maps. A weak reference lets a program find an object without keeping it alive. A weak map holds its keys weakly, so an entry goes when the object that it is stored under goes. JavaScript has
WeakMapandWeakRef, Python hasWeakKeyDictionaryandWeakValueDictionary, Java hasWeakHashMap, Go hasweak.Pointer, and .NET hasConditionalWeakTable.212216193531 The ECMAScript specification says thatWeakMapcan associate state with an object without leaking memory.21 - The lapsed listener. A subject in the Observer pattern keeps a list of its observers. An observer that never unsubscribes stays alive as long as the subject does. The DOM
addEventListenertakes anAbortSignal, and aborting it removes the listener.23 A C# event keeps each subscriber until it unsubscribes with-=.28 Node.js prints a warning about a possible memory leak when an emitter gets more than 10 listeners for one event.24 - Captured variables. A closure keeps each variable that it captures. A callback that stays registered can keep a large object alive, even when it reads only one field of it.
- Goroutine and thread leaks. A goroutine that blocks forever keeps its stack and the objects that the stack refers to.
runtime.NumGoroutinereturns the number of goroutines that exist.32 Acontextcancel function ends the work of the goroutines that use the context. Code that never calls it leaks the context until its parent ends, andgo vetchecks that each path calls it.33 The same applies to Thread in other languages. - Timers. A timer that is still scheduled is reachable from the runtime, and so is its callback. The Go documentation of
time.NewTickersays the collector can recover a ticker that no code refers to, even when nobody stopped it.36 - Reference cycles. Reference counting cannot free a cycle of objects that refer to each other. Python has a cycle collector for this; Rust and C++ need a weak pointer on one side. Garbage collection has examples.
- Resource leaks. A file, socket or lock that the program never releases is a leak of a different resource. CWE-401 is a child of CWE-772, Missing Release of Resource after Effective Lifetime, and of CWE-404, Improper Resource Shutdown or Release.1
- The opposite error. A leak frees memory too late or never. A Use after free frees it too early. A fix for one can cause the other, so each heap object needs one clear owner. See Stack and heap for where objects live.
Pitfalls
An early return skips the free
Each exit path of a function must free what the function allocated. Here, the error path returns before free.
This code has a memory error, on purpose, and the sanitizer reports it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Returns 0 and stores the port in *port when text is a valid port number.
int parse_port(const char *text, int *port) {
char *copy = malloc(strlen(text) + 1);
if (copy == NULL) {
return -1;
}
strcpy(copy, text);
char *end = NULL;
long value = strtol(copy, &end, 10);
if (*end != '\0' || value <= 0 || value > 65535) {
return -1; // copy leaks on this path
}
free(copy);
*port = (int)value;
return 0;
}
int main(void) {
int port = 0;
printf("8080: %d\n", parse_port("8080", &port));
printf("80x: %d\n", parse_port("80x", &port));
}
LeakSanitizer reports the copy from the second call. The fix gives the function one exit, and the free comes before it.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Returns 0 and stores the port in *port when text is a valid port number.
int parse_port(const char *text, int *port) {
char *copy = malloc(strlen(text) + 1);
if (copy == NULL) {
return -1;
}
strcpy(copy, text);
char *end = NULL;
long value = strtol(copy, &end, 10);
int status = -1;
if (*end == '\0' && value > 0 && value <= 65535) {
*port = (int)value;
status = 0;
}
free(copy);
return status;
}
int main(void) {
int port = 0;
printf("8080: %d\n", parse_port("8080", &port));
printf("80x: %d\n", parse_port("80x", &port));
}
8080: 0
80x: -1
In C++, make the owner a local object, so each exit path frees it. The C++ example shows the same leak on a path that throws.
A cache without a limit
functools.cache saves every result it computes. It is the same as lru_cache(maxsize=None), and that cache can grow without bound.15
This code runs but gives a wrong answer on purpose.
import functools
@functools.cache
def render(page_id):
return f"<html>page {page_id}</html>"
for page_id in range(10_000):
render(page_id)
print("cached results:", render.cache_info().currsize)
cached results: 10000
A cache in a long-running process needs a limit. lru_cache(maxsize=256) keeps the 256 results that the program used last.15
import functools
@functools.lru_cache(maxsize=256)
def render(page_id):
return f"<html>page {page_id}</html>"
for page_id in range(10_000):
render(page_id)
print("cached results:", render.cache_info().currsize)
cached results: 256
The Java example does the same with a LinkedHashMap that drops its eldest entry.20
A listener that nobody removes
A publisher keeps a reference to each subscriber. When a subscriber closes but does not unsubscribe, the publisher keeps it alive.
This code runs but gives a wrong answer on purpose.
import weakref
class Publisher:
def __init__(self):
self.listeners = []
def subscribe(self, listener):
self.listeners.append(listener)
class Panel:
def __init__(self, publisher):
self.pixels = bytearray(100_000)
publisher.subscribe(self.refresh)
def refresh(self):
pass
def close(self):
self.pixels = None
feed = Publisher()
panel = Panel(feed)
probe = weakref.ref(panel)
panel.close()
del panel
print("panel alive after close:", probe() is not None)
panel alive after close: True
The bound method self.refresh refers to the panel, so the list keeps the panel. The fix removes the listener in close. weakref.WeakMethod is another fix: it refers to a bound method without keeping its object alive.16
import weakref
class Publisher:
def __init__(self):
self.listeners = []
def subscribe(self, listener):
self.listeners.append(listener)
def unsubscribe(self, listener):
self.listeners.remove(listener)
class Panel:
def __init__(self, publisher):
self.publisher = publisher
self.pixels = bytearray(100_000)
publisher.subscribe(self.refresh)
def refresh(self):
pass
def close(self):
self.publisher.unsubscribe(self.refresh)
self.pixels = None
feed = Publisher()
panel = Panel(feed)
probe = weakref.ref(panel)
panel.close()
del panel
print("panel alive after close:", probe() is not None)
print("listeners left:", len(feed.listeners))
panel alive after close: False
listeners left: 0
The JavaScript, TypeScript and C# examples show the same leak with EventTarget, a typed emitter and a C# event.
A closure keeps a large object
A closure keeps the whole object that it captures, not only the fields that it reads.
This code runs but gives a wrong answer on purpose.
import weakref
class Upload:
def __init__(self, name):
self.name = name
self.data = bytearray(1_000_000)
def on_done(upload):
return lambda: f"done: {upload.name}"
upload = Upload("a.png")
probe = weakref.ref(upload)
callback = on_done(upload)
del upload
print(callback(), "| upload alive:", probe() is not None)
done: a.png | upload alive: True
Copy the field that the callback needs into a local variable, and let the closure capture only that.
import weakref
class Upload:
def __init__(self, name):
self.name = name
self.data = bytearray(1_000_000)
def on_done(upload):
name = upload.name
return lambda: f"done: {name}"
upload = Upload("a.png")
probe = weakref.ref(upload)
callback = on_done(upload)
del upload
print(callback(), "| upload alive:", probe() is not None)
done: a.png | upload alive: False
A goroutine that blocks forever
A goroutine that sends on a channel that nobody reads never ends. The collector does not stop it, and its stack stays in memory. The Go example starts ten workers, reads one result and leaks nine goroutines. The fix passes a context and calls its cancel function on return.33 A goroutine profile from runtime/pprof groups the goroutines by stack, so a stack whose count grows points to the leak.34 The Go runtime also has a goroutineleak profile. It uses the collector to find goroutines that wait on a channel or lock that no runnable goroutine can reach.3738 It can miss a leak when a global variable reaches the channel.38
A weak map whose values refer to their keys
A weak map holds its keys weakly but its values strongly. If a value refers to the object that it is stored under, the map keeps that object alive through the value. Then the entry never goes. The Java documentation of WeakHashMap warns about this.19
This code runs but gives a wrong answer on purpose.
import weakref
class Session:
pass
class Info:
def __init__(self, session):
self.session = session
info = weakref.WeakKeyDictionary()
session = Session()
info[session] = Info(session)
del session
print("entries after del:", len(info))
entries after del: 1
Keep the values free of references to their keys. If a value needs the object that it belongs to, give it a weak reference to that object.
import weakref
class Session:
pass
class Info:
def __init__(self, session):
self.session = weakref.ref(session)
info = weakref.WeakKeyDictionary()
session = Session()
info[session] = Info(session)
del session
print("entries after del:", len(info))
entries after del: 0
Cost
- LeakSanitizer. It adds almost no overhead until the process ends. Then it runs one extra leak detection phase.6 With AddressSanitizer, the typical slowdown is 2x.8
- Valgrind Memcheck. The program runs much slower under Memcheck, for example 20 to 30 times, and it uses a lot more memory.4 It needs no rebuild, because it instruments the machine code at run time.5
- Purify. Its authors measured a slowdown of less than a factor of three for programs with its checks.2
- tracemalloc. Each traced frame costs memory and CPU time, so
tracemalloc.start(nframe)with a largernframecosts more.tracemalloc.get_tracemalloc_memory()reports the memory that the tracer itself uses.14 - Heap snapshots in Node.js.
v8.writeHeapSnapshot()needs about twice the size of the heap. It is synchronous, so it blocks the event loop until the file is complete.26 - .NET heap dumps.
dotnet-gcdumpstarts a full generation 2 collection, which can suspend the runtime for a long time in a large heap.29 - The leak itself. A leak in a collected language also makes the collector work harder. The JVM reports "GC overhead limit exceeded" after five collections in a row that use over 98% of the time. Each of them recovers less than 2% of the heap. When the heap is full, the error is "Java heap space".18
History
- 1992. Reed Hastings and Bob Joyce presented Purify at the Winter USENIX Conference. It inserted checks into object code and found leaked blocks with "a novel adaptation of garbage collection techniques".2
- 2002. Valgrind had its first release. Nicholas Nethercote and Julian Seward described its design at PLDI in 2007.5
- 2014. Clang 3.4, released on 2 January 2014, added LeakSanitizer as an experimental leak detector to use with AddressSanitizer.910
- 2024. Go 1.23 let the collector recover tickers and timers that no code refers to, even when nobody stopped them. Earlier, such a ticker stayed in memory.36
- 2026. Go 1.26 added an experimental
goroutineleakprofile, enabled withGOEXPERIMENT=goroutineleakprofile. The notes credit Vlad Saioc of Uber for the work.37 Go 1.27 made the profile generally available.38
References
- CWE-401: Missing Release of Memory after Effective Lifetime, the weakness id, its Variant abstraction, and its parents CWE-772 and CWE-404
- Reed Hastings and Bob Joyce, Purify: Fast Detection of Memory Leaks and Access Errors, Proceedings of the Winter 1992 USENIX Conference, Abstract; Introduction; section 5, Memory Leaks
- Valgrind User Manual, Memcheck, a memory error detector, 4.2.8 Memory leak detection
- The Valgrind Quick Start Guide, Running your program under Memcheck
- Nicholas Nethercote and Julian Seward, Valgrind: A Framework for Heavyweight Dynamic Binary Instrumentation, PLDI 2007, section 3, How Valgrind Works
- Clang documentation, LeakSanitizer, Introduction; Usage; Suppressing memory leaks; Supported Platforms
- google/sanitizers wiki, LeakSanitizer design document, Operation
- Clang documentation, AddressSanitizer, Introduction; Memory leak detection
- Clang 3.4 Release Notes, What's New in Clang 3.4
- LLVM Download Page, the release list, 02 Jan 2014, 3.4
- ISO/IEC 9899:2024 working draft N3220, Programming languages, C, 7.24.3.7 The realloc function, paragraphs 3 and 4
- Working Draft, Programming Languages, C++, [except.ctor] Stack unwinding, paragraphs 1 and 2
- Working Draft, Programming Languages, C++, [unique.ptr.general] paragraph 1 and Note 1
- The Python Standard Library, tracemalloc, Trace memory allocations, Python 3.14, the introduction; Snapshot.compare_to; tracemalloc.start and get_tracemalloc_memory
- The Python Standard Library, functools, Python 3.14, functools.cache and functools.lru_cache
- The Python Standard Library, weakref, Weak references, Python 3.14, the introduction; WeakKeyDictionary; WeakValueDictionary; WeakMethod
- The Java Language Specification, Java SE 25 Edition, 12.6.1 Implementing Finalization
- Java Platform, Standard Edition Troubleshooting Guide, Release 25, Troubleshoot Memory Leaks, The java.lang.OutOfMemoryError Error; Diagnosing Java Memory Leaks, Heap Dumps and Java Flight Recorder
- Java SE 25 API, java.util.WeakHashMap, class description and implementation note
- Java SE 25 API, java.util.LinkedHashMap, class description, access order; removeEldestEntry
- ECMA-262, ECMAScript 2026 Language Specification, 24.3 WeakMap Objects
- ECMA-262, ECMAScript 2026 Language Specification, 26.1 WeakRef Objects
- DOM Living Standard, 2.7 Interface EventTarget, addEventListener, removeEventListener, AddEventListenerOptions signal and once
- Node.js documentation, Events, events.defaultMaxListeners; events.getEventListeners
- Node.js documentation, Command-line API, --heapsnapshot-signal=signal
- Node.js documentation, V8, v8.writeHeapSnapshot
- Chrome DevTools, Record heap snapshots, Comparison view; The Retainers section; Objects retained by detached nodes
- C# Programming Guide, How to subscribe to and unsubscribe from events, Unsubscribing
- .NET documentation, Heap analysis tool (dotnet-gcdump), the introduction; dotnet-gcdump collect
- .NET documentation, Dump collection and analysis utility (dotnet-dump), Analyze SOS commands, dumpheap and gcroot
- .NET API, ConditionalWeakTable<TKey,TValue>, Remarks
- Go standard library, package runtime, func NumGoroutine
- Go standard library, package context, Overview; Example WithCancel
- Go standard library, package runtime/pprof, type Profile, the predefined profiles and the heap profile
- Go standard library, package weak, type Pointer
- Go standard library, package time, func NewTicker
- Go 1.26 Release Notes, Goroutine leak profiles
- Go 1.27 Release Notes, Goroutine leak profiles
- Rust standard library, std::mem::forget, Safety
- Rust standard library, std::boxed::Box, Box::leak
- The Rust Programming Language, 15.6 Reference Cycles Can Leak Memory, the introduction
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 51XM6E Edit this page History Report an error Markdown