# 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.

Source: https://fullbytedeveloper.com/blog/stack-vs-heap-part-2-leaks
Published here: 2026-11-21

Part 2 after [stack vs heap memory](/blog/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:

```c title="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

| Model | Who cleans up? | When dynamic storage ends | Leak shape |
|---|---|---|---|
| C / C++ | You (`free` / `delete` / RAII) | Explicit free or destructor / smart pointer drop | Lost pointer, or never free [4] [8] [9] |
| Rust | Owner `Drop` | Owner leaves scope | Cycles, `mem::forget`, `Box::leak` (still memory-safe) [1] [3] |
| Python | Refcount + cyclic GC | Refcount hits 0, or cyclic collector reclaims | Still reachable from a root; cycles among unreachable objects are collected [6] |
| Go | Tracing GC | Unreachable from roots | Logical 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.

Image: 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.
https://fullbytedeveloper.com/media/stack-vs-heap-part-2-leaks/lifetime-table.webp
Lifetimes differ by language. A leak is heap you still retain after you no longer need it.

## Sources

1. [Rust Book: Reference Cycles Can Leak Memory, accessed 2026-11-20](https://doc.rust-lang.org/book/ch15-06-reference-cycles.html)
2. [Rust Book: What Is Ownership?, accessed 2026-11-20](https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html)
3. [Rust std::mem::forget, accessed 2026-11-20](https://doc.rust-lang.org/std/mem/fn.forget.html)
4. [cppreference: free, accessed 2026-11-20](https://en.cppreference.com/w/c/memory/free)
5. [cppreference: Undefined behavior, accessed 2026-11-20](https://en.cppreference.com/w/cpp/language/ub)
6. [Python docs: gc module, accessed 2026-11-20](https://docs.python.org/3/library/gc.html)
7. [Go GC guide, accessed 2026-11-20](https://go.dev/doc/gc-guide)
8. [Illinois CS 225: Stack and Heap Memory, accessed 2026-11-20](https://courses.physics.illinois.edu/cs225/sp2025/resources/stack-heap/)
9. [Microsoft Learn: RAII, related C++ teaching](https://learn.microsoft.com/en-us/cpp/cpp/object-lifetime-and-resource-management-modern-cpp)
