Full Byte Developer.

Stack vs heap part 2: leaks and lifetimes

Compare C, Rust, Python, and Go lifetimes. Keep an owner pointer, free once, and skip crash theater for UB.

Published here · 9 sources

Part 2 after stack vs heap memory. Stack (automatic) storage ends with the scope. Heap / dynamic storage lives until an explicit free (C/C++), a drop of the owner (Rust), or until the GC finds the object unreachable (Python, Go, and other GC languages) [2] [6] [7] [8]. A leak is retaining heap storage after it is no longer needed, or losing the last pointer without freeing [8].

Keep ownership when you free in C

Safe pattern: allocate, keep an owner pointer, free once, null the pointer. Compile with warnings enabled and run on your own machine:

leak_then_free.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    size_t n = 1024;
    char *p = malloc(n);
    if (!p) {
        fprintf(stderr, "malloc failed\n");
        return 1;
    }
    memset(p, 'A', n - 1);
    p[n - 1] = '\0';

    char *keep = p;   /* ownership retained */
    p = NULL;         /* drop working pointer only */

    printf("allocated %zu bytes; working ptr dropped; freeing via keep\n", n);
    free(keep);
    keep = NULL;
    printf("freed cleanly\n");
    return 0;
}
bash
cc -Wall -Wextra -o leak_then_free leak_then_free.c
./leak_then_free

You should see the two printf lines and exit 0. This demo shows the ownership pattern; optional tools such as Valgrind can help catch leaks on your machine when you install them. cppreference: free of a null pointer is a no-op; freeing a non-allocation pointer, double-free, and use-after-free are undefined behavior [4] [5].

Compare lifetimes across languages

ModelWho cleans up?When dynamic storage endsLeak shape
C / C++You (free / delete / RAII)Explicit free or destructor / smart pointer dropLost pointer, or never free [4] [8] [9]
RustOwner DropOwner leaves scopeCycles, mem::forget, Box::leak (still memory-safe) [1] [3]
PythonRefcount + cyclic GCRefcount hits 0, or cyclic collector reclaimsStill reachable from a root; cycles among unreachable objects are collected [6]
GoTracing GCUnreachable from rootsLogical leaks from kept map/slice/goroutine refs [7]

Rust Book ownership: each value has an owner; when the owner leaves scope, the value is dropped [2]. Lifetimes on references describe how long references are valid; they do not make values live longer. Rust Book ch15-06: "Preventing memory leaks entirely is not one of Rust's guarantees, meaning memory leaks are memory safe in Rust" [1]. std::mem::forget skips destructors on purpose; prefer documented APIs such as Box::leak / ManuallyDrop when that is intentional [3].

Python's gc module supplements reference counting for cycles; gc.set_debug(gc.DEBUG_LEAK) helps investigation [6]. Go's GC guide describes the standard toolchain tracing collector and GOGC as a heap-growth trade-off control [7]. Do not cite the Go Memory Model as a GC lifetime tutorial; that document is about concurrency visibility.

Teach undefined behavior without crash theater

cppreference: undefined behavior means there are no restrictions on the behavior of the program [5]. Compilers may assume UB never happens. Teaching limit for this Senior page: name operations the standard treats as UB (double-free, free of a non-malloc pointer, use-after-free, out-of-bounds access) and stop [4] [5]. Do not stage segfault demos or claim a specific crash is required.

Illinois CS 225 notes match the practical habit: set a pointer to null after delete, and remember leaks hurt long-running servers more than tiny short programs (qualitative, no invented metrics) [8].

You now have a cross-language lifetime table, a safe free demo, and a stop line before UB spectacle.

Send this to the friend learning C who keeps freeing the same pointer twice.

Table of C/C++, Rust, Python, and Go cleanup owners and leak shapes, plus a UB teaching limit card that names double-free and use-after-free without crash theater. No people.
Lifetimes differ by language. A leak is heap you still retain after you no longer need it.

Keep this guide

By Full Byte Developer

Filed under Dev explainers

Questions about this guide

Does Rust make leaks impossible?

No. The Rust Book says preventing memory leaks entirely is not one of Rust's guarantees. Reference cycles, mem::forget, and Box::leak can retain memory while remaining memory-safe.

What is a memory leak in C?

You allocate with malloc (or friends) and lose the last pointer without free, or you never free. Illinois CS 225 teaching notes frame the same idea for new/delete in C++.

Is a Python object with refcount zero always collected immediately?

Reference counting frees many objects at zero. Cyclic garbage needs the cyclic collector. Application leaks are usually objects still reachable from a root such as a global cache.

Does undefined behavior always crash?

No. cppreference states there are no restrictions on the behavior of a program with undefined behavior. Name the UB class. Do not treat one machine's crash as a proof.

Sources

Next in this stack