M02 · Memory Model

Reachability, Garbage Collection and RAII

An object is garbage when no chain of references from the running program leads to it. Garbage collectors find such objects by tracing from the roots; reference counting frees them when their count drops to zero but misses cycles; C++ frees them when their owner is destroyed. Releasing files and locks is a separate job that should never wait for any of these.

~35 minBeginnerC# · Python · Java · C++
Curriculum: M02 Memory Model · 5 of 5 lessons available

You will be able to

  • Define roots and reachability, and decide which objects in a graph are garbage.
  • Trace the mark and sweep phases, and explain why cycles do not stop a tracing collector.
  • Explain why reference counting cannot free cycles, and how CPython and std::shared_ptr deal with that.
  • Use deterministic cleanup in each language: using, with, try-with-resources and destructors.

Helpful before this lesson

  • M01 Algorithmic Thinking — Turn a vague task into precise inputs, outputs and constraints, then argue that a solution is correct.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A program can only use an object if it can reach it. The starting points are the roots: local variables of calls that are still running, static fields, and a few runtime-internal references. Follow every reference from the roots, and from what they reach, and so on: everything you can get to is live. Everything else is garbage, because no code can ever touch it again, so its memory can be reused.

Reachability, not "is anyone pointing at it", is the rule. Two objects that refer only to each other are garbage if nothing reachable refers to either.

Mark and sweep

The lab runs the textbook tracing algorithm on a small object graph:

  1. Mark: push every root's object on a work stack and mark it. Repeatedly pop an object and scan its references; mark and push each target not marked yet. An already-marked target is skipped, which is what makes cycles terminate.
  2. Sweep: walk all objects; unmarked ones are garbage and their memory is reclaimed.

Marking visits each live object and each of its references once: O(live objects + references). Sweeping touches every object in the heap.

Production collectors are far more refined. The .NET GC and the HotSpot collectors are generational (most objects die young, so young objects are collected often and cheaply), they usually compact live objects to remove fragmentation, and several do much of their work concurrently with the program. The rule they implement is still reachability, and they choose when to run. You cannot predict the moment an unreachable object's memory is reclaimed.

Reference counting and cycles

Another strategy keeps a count of references to each object and frees it the moment the count drops to zero. Freeing is immediate and predictable, but a cycle keeps every count above zero forever.

  • CPython uses reference counting for most objects, so non-cyclic garbage is freed at once. A separate cycle collector (the gc module) periodically finds groups of objects that are only reachable from each other and frees them. In the lab's Python rules, the sweep says which garbage reference counting would already have freed and which needed the cycle collector.
  • C++ std::shared_ptr is reference counting without any cycle collector. Two objects holding shared_ptrs to each other are never freed: a leak. Make one direction a std::weak_ptr, which observes without owning. In the lab's C++ rules, unreachable cycles are shown as leaked.

Deterministic cleanup is a separate job

Memory is one resource among many. Files, sockets, locks and database connections must be released at a known point, not "eventually". Every language has a construct that runs cleanup when a scope ends, including when an exception leaves it:

Language Construct What runs
C# using statement or using var declaration Dispose()
Java try-with-resources close() (of AutoCloseable), in reverse order
Python with statement the context manager's __exit__()
C++ any object with automatic storage (RAII) its destructor, in reverse order of construction

In C#, Java and Python, cleanup and memory reclamation are separate events: after Dispose, close or __exit__, the object itself is still an ordinary object until it becomes unreachable. In C++ they coincide: the destructor runs and the storage is released at the end of the scope. Turn on the lab's scoped resource to see the difference.

Avoid relying on finalizers for cleanup. C# finalizers run on the collector's schedule, possibly never before the process exits; Java's finalize is deprecated for removal (use Cleaner as a safety net, try-with-resources as the real mechanism); Python's __del__ runs when CPython's count reaches zero but later, or not at all, on other implementations.

Common mistakes

  • Expecting the garbage collector to close files promptly.
  • Assuming an object is freed "when the method ends" in C# or Java.
  • Building parent ↔ child links with shared_ptr in both directions.
  • Keeping a long-lived reference (a static cache, an event subscription) to objects you think are garbage: they are reachable, so they are not collected. That is how leaks happen in GC languages.

Edge cases

  • No roots: everything is garbage.
  • A self-reference (A → A) does not keep A alive in a tracing collector.
  • Garbage that a cycle points to (but which is not itself in the cycle) is also stuck under pure reference counting until the cycle is broken.

Worked practice

1. Objects A, B, C, D; references A→B, C→D, D→C; root A. Which are garbage? What happens to them in CPython, and with shared_ptr links in C++?

Answer

C and D are garbage (only they refer to each other). In CPython their reference counts stay at 1, so the cycle collector frees them. With shared_ptr in both directions they leak.

2. Why does marking terminate on a graph with cycles?

Answer

Each object is pushed only when it is first marked, and a marked object is never pushed again. So each object is scanned at most once, and the work stack eventually empties.

Summary

  • Live means reachable from a root; everything else is garbage.
  • Tracing collectors mark from the roots and reclaim the rest, cycles included, at a time they choose.
  • Reference counting frees immediately but misses cycles: CPython adds a cycle collector, shared_ptr needs weak_ptr.
  • Release resources deterministically with using, try-with-resources, with or RAII.

Full implementation

Mark and sweep in four languages against one shared fixture of object graphs (cycles, no roots, shared targets, self-references), plus deterministic cleanup (using, with, try-with-resources, RAII), CPython freeing a cycle only after gc.collect(), and a weak_ptr back link in C++.

namespace Bekadan.Dsa.Examples.Memory;
 
/// <summary>
/// Garbage is decided by reachability from roots. Collect runs the mark-and-sweep idea
/// on a small object graph (the .NET GC is far more elaborate: generational, compacting,
/// and it decides when to run). DeterministicCleanup shows that releasing a resource is a
/// separate matter: using calls Dispose at a known point.
/// </summary>
public static class Reachability
{
    public static (List<string> Reachable, List<string> Garbage) Collect(
        IReadOnlyList<string> objects, IReadOnlyList<(string From, string To)> references, IReadOnlyList<string> roots)
    {
        var refs = references.ToLookup(r => r.From, r => r.To);
        var marked = new HashSet<string>();
        var work = new Stack<string>();
        foreach (var root in roots)
        {
            if (marked.Add(root)) work.Push(root);
        }
        while (work.Count > 0)
        {
            var current = work.Pop();
            foreach (var target in refs[current])
            {
                if (marked.Add(target)) work.Push(target);   // already marked: skip (this is what ends cycles)
            }
        }
        var reachable = new List<string>();
        var garbage = new List<string>();
        foreach (var obj in objects)
        {
            if (marked.Contains(obj))
            {
                reachable.Add(obj);
            }
            else
            {
                garbage.Add(obj);                        // a tracing GC reclaims it, cycles included
            }
        }
        return (reachable, garbage);
    }
 
    public sealed class TrackedResource(string name, List<string> log) : IDisposable
    {
        public void Use() => log.Add($"use {name}");
 
        public void Dispose() => log.Add($"dispose {name}");
    }
 
    public static List<string> DeterministicCleanup()
    {
        var log = new List<string>();
        using (var file = new TrackedResource("file", log))
        {
            file.Use();
        }                                                // Dispose runs here, whatever the GC does
        log.Add("after using");
        Check(log.SequenceEqual(["use file", "dispose file", "after using"]), "Dispose runs at the end of the using block");
        return log;
    }
 
    private static void Check(bool condition, string claim)
    {
        if (!condition) throw new InvalidOperationException($"Claim failed: {claim}");
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Memory/Reachability.cs

"""Reachability decides garbage; with-blocks decide when resources are released.
 
CPython frees most objects when their reference count drops to zero; objects in
unreachable cycles wait for the cyclic garbage collector (the gc module). The
mark-and-sweep below shows the reachability rule itself.
"""
 
import gc
import weakref
from types import TracebackType
 
 
def _check(condition: bool, claim: str) -> None:
    if not condition:
        raise AssertionError(f"Claim failed: {claim}")
 
 
def collect(objects: list[str], references: list[tuple[str, str]], roots: list[str]) -> tuple[list[str], list[str]]:
    refs: dict[str, list[str]] = {}
    for source, target in references:
        refs.setdefault(source, []).append(target)
    marked: set[str] = set()
    work: list[str] = []
    for root in roots:
        if root not in marked:
            marked.add(root)
            work.append(root)
    while work:
        current = work.pop()
        for target in refs.get(current, []):
            if target not in marked:  # already marked: skip (this is what ends cycles)
                marked.add(target)
                work.append(target)
    reachable: list[str] = []
    garbage: list[str] = []
    for obj in objects:
        if obj in marked:
            reachable.append(obj)
        else:
            garbage.append(obj)
    return reachable, garbage
 
 
class TrackedResource:
    def __init__(self, name: str, log: list[str]) -> None:
        self.name = name
        self.log = log
 
    def __enter__(self) -> "TrackedResource":
        return self
 
    def __exit__(self, kind: type[BaseException] | None, error: BaseException | None, trace: TracebackType | None) -> None:
        self.log.append(f"exit {self.name}")
 
    def use(self) -> None:
        self.log.append(f"use {self.name}")
 
 
def deterministic_cleanup() -> list[str]:
    log: list[str] = []
    with TrackedResource("file", log) as file:  # __exit__ runs the moment this block ends
        file.use()
    log.append("after with")
    _check(log == ["use file", "exit file", "after with"], "__exit__ runs at the end of the with-block")
    return log
 
 
class Node:
    def __init__(self) -> None:
        self.other: "Node | None" = None
 
 
def cycle_needs_the_collector() -> tuple[bool, bool]:
    """(alive after the last name is deleted, freed after gc.collect()) for a two-object cycle."""
    gc.disable()
    try:
        a, b = Node(), Node()
        a.other, b.other = b, a
        probe = weakref.ref(a)
        del a, b
        alive = probe() is not None  # each still has a reference count of 1, from the other
        gc.collect()
        return alive, probe() is None
    finally:
        gc.enable()

Tested on CPython 3.14.0 · examples/python/dsa_examples/memory_reachability.py

package dev.bekadan.dsa.memory;
 
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
/**
 * Garbage is decided by reachability from roots. collect runs the mark-and-sweep idea
 * on a small object graph (real JVM collectors are generational and concurrent, and
 * choose when to run). deterministicCleanup shows that releasing a resource is a
 * separate matter: try-with-resources calls close() at a known point.
 */
public final class Reachability {
    private Reachability() {
    }
 
    /** Returns [reachable, garbage], each in object order. references holds {from, to} pairs. */
    public static List<List<String>> collect(List<String> objects, List<String[]> references, List<String> roots) {
        Map<String, List<String>> refs = new HashMap<>();
        for (String[] r : references) {
            refs.computeIfAbsent(r[0], key -> new ArrayList<>()).add(r[1]);
        }
        Set<String> marked = new HashSet<>();
        Deque<String> work = new ArrayDeque<>();
        for (String root : roots) {
            if (marked.add(root)) work.push(root);
        }
        while (!work.isEmpty()) {
            String current = work.pop();
            for (String target : refs.getOrDefault(current, List.of())) {
                if (marked.add(target)) work.push(target);   // already marked: skip (this is what ends cycles)
            }
        }
        List<String> reachable = new ArrayList<>();
        List<String> garbage = new ArrayList<>();
        for (String obj : objects) {
            if (marked.contains(obj)) {
                reachable.add(obj);
            } else {
                garbage.add(obj);                         // a tracing GC reclaims it, cycles included
            }
        }
        return List.of(reachable, garbage);
    }
 
    /** A resource that records when it is used and closed. */
    public static final class TrackedResource implements AutoCloseable {
        private final String name;
        private final List<String> log;
 
        public TrackedResource(String name, List<String> log) {
            this.name = name;
            this.log = log;
        }
 
        public void use() {
            log.add("use " + name);
        }
 
        @Override
        public void close() {
            log.add("close " + name);
        }
    }
 
    public static List<String> deterministicCleanup() {
        List<String> log = new ArrayList<>();
        try (TrackedResource file = new TrackedResource("file", log)) {
            file.use();
        }                                                 // close() runs here, whatever the GC does
        log.add("after try");
        check(log.equals(List.of("use file", "close file", "after try")), "close() runs at the end of try-with-resources");
        return log;
    }
 
    private static void check(boolean condition, String claim) {
        if (!condition) {
            throw new AssertionError("Claim failed: " + claim);
        }
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/memory/Reachability.java

#pragma once
 
#include <cassert>
#include <memory>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
 
namespace bekadan::dsa::memory {
 
// C++ has no tracing garbage collector. collect shows the reachability rule that
// tracing collectors in other languages apply; in C++ lifetime comes from owners
// (scopes, unique_ptr, shared_ptr), and destruction happens at a known point.
struct Collected {
    std::vector<std::string> reachable;
    std::vector<std::string> garbage;
};
 
inline Collected collect(const std::vector<std::string>& objects, const std::vector<std::pair<std::string, std::string>>& references,
                         const std::vector<std::string>& roots) {
    std::unordered_map<std::string, std::vector<std::string>> refs;
    for (const auto& [from, to] : references) refs[from].push_back(to);
    std::unordered_set<std::string> marked;
    std::vector<std::string> work;
    for (const auto& root : roots) {
        if (marked.insert(root).second) work.push_back(root);
    }
    while (!work.empty()) {
        const std::string current = work.back();
        work.pop_back();
        const auto it = refs.find(current);
        if (it == refs.end()) continue;
        for (const auto& target : it->second) {
            if (marked.insert(target).second) work.push_back(target);  // already marked: skip (this is what ends cycles)
        }
    }
    Collected result;
    for (const auto& obj : objects) {
        if (marked.contains(obj)) {
            result.reachable.push_back(obj);
        } else {
            result.garbage.push_back(obj);
        }
    }
    return result;
}
 
// RAII: the destructor releases the resource when the owner goes out of scope.
class TrackedResource {
public:
    TrackedResource(std::string name, std::vector<std::string>& log) : name_(std::move(name)), log_(log) {}
    TrackedResource(const TrackedResource&) = delete;
    TrackedResource& operator=(const TrackedResource&) = delete;
    ~TrackedResource() { log_.push_back("destroy " + name_); }
    void use() { log_.push_back("use " + name_); }
 
private:
    std::string name_;
    std::vector<std::string>& log_;
};
 
inline std::vector<std::string> deterministic_cleanup() {
    std::vector<std::string> log;
    {
        TrackedResource file("file", log);
        file.use();
    }  // the destructor runs here: cleanup and freeing happen together
    log.push_back("after scope");
    assert((log == std::vector<std::string>{"use file", "destroy file", "after scope"}));
    return log;
}
 
// Two shared_ptrs pointing at each other would keep each other alive forever (a leak).
// Making the back link a weak_ptr breaks the cycle.
struct Node {
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> back;
};
 
inline bool weak_back_link_lets_the_pair_go() {
    std::weak_ptr<Node> probe;
    {
        auto a = std::make_shared<Node>();
        auto b = std::make_shared<Node>();
        a->next = b;
        b->back = a;
        probe = a;
        assert(!probe.expired());
    }
    return probe.expired();
}
 
}  // namespace bekadan::dsa::memory

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/memory/reachability.hpp

References