flowchart TD root["root: symbol table"] --> B["B (marked)"] & C["C (marked)"] B --> D["D (marked)"] E["E (unreachable)"] --> F["F (unreachable)"]
6.9 Garbage Collection
6.9.1 Motivation
An R session allocates constantly: in interpreted code every arithmetic result, argument list and promise is a new object on R’s heap, and byte-compiled code avoids only part of that by keeping scalar results on its own stack. Garbage collection is how that memory comes back. The collector finds all data the program can still reach and frees the rest, so R code never frees anything by hand.
The alternative is manual memory management, where the programmer writes code to deallocate objects. It is fast and error-prone: freeing too early gives use-after-free crashes, and forgetting gives leaks. For an interactive language used for quick scripts, asking every script to free its own memory is untenable.
6.9.2 Mental model
Intuition: marking and sweeping
Imagine your program holds a graph of objects. Some objects are reachable: your code can reach them by following pointers from roots. Others are unreachable. Unreachable objects are garbage.
The collector traces from the roots. It marks every object it finds. It then walks the entire heap and sweeps up unmarked objects.
A simple example makes this concrete. Your global environment holds a variable x that points to a list. The list holds two numbers. Those numbers are reachable. Your code also creates a temporary data frame in a function. When the function returns, nothing points to that data frame. The collector marks the list and numbers. It does not mark the data frame. In the sweep phase, it reclaims the data frame’s memory.
The collector traces from roots and marks reachable objects. E and F are unreachable and will be freed in the sweep phase.
Mechanics: tracing vs. reference counting
Two major strategies exist: tracing and reference counting. Tracing walks the object graph from roots. Reference counting decorates each object with a counter. Decrement the counter when a pointer disappears. Free the object when the counter reaches zero.
| Strategy | Tracing | Reference counting |
|---|---|---|
| Work happens | at collection time, from the roots | on every pointer store |
| Cycles | freed | leaked unless a cycle collector runs |
| Pauses | grow with the live data traced | usually short; freeing a large structure can cascade |
| Concurrency | the collector needs a consistent view of the heap | every count update must be synchronized |
A simple tracing collector pauses the program to mark consistently. Reference counting writes to every object that gains or loses a pointer. R chose tracing, and specifically generational tracing. Young objects tend to die fast and older objects tend to live, so a generational collector scans young objects often and old objects rarely. R also keeps reference counts, described in Copy-on-Modify, but it uses them to decide when to copy, never when to free.
Runtime detail: mark-and-sweep over SEXP nodes
GNU R represents all data as nodes reached through SEXP pointers. A SEXP points to a C struct, SEXPREC, whose header carries the fields the garbage collector needs.
The first is the mark bit in the 64-bit sxpinfo word. During a collection the collector sets it on every object it reaches, and the objects left unmarked are freed. Between collections the bit stays set on old objects; a new object is one whose bit is clear.
The second is the gcgen bit, which records the generation. R keeps three generations: new objects, and two old generations numbered 0 and 1. An object that survives a collection moves up one, from new to old generation 0, and from 0 to 1 the next time generation 0 is collected. Older generations are collected less often, which keeps most pauses short.
The third is a pair of link pointers, gengc_next_node and gengc_prev_node. Every node sits on a circular doubly-linked list for its node class and generation, so the collector can walk one generation, or move a node from one list to another, without touching the rest of the heap.
The collector writes header fields of every object it reaches during a collection, so even an object that R code only reads gets written.
A generational collector needs a mechanism to catch writes that violate generation boundaries. If an old object points to a young object, a young-only collection can miss that young object. A write barrier detects this. Every store into a SEXPREC field checks the generation. If an old object gets a pointer to a young object, the collector records that fact. On the next young-only collection, it scans that old object.
6.9.3 Roots and reachability
The collector must know where to start. A GC root is a place tracing starts from: a global variable, a stack slot, a table the runtime keeps. Anything not reachable from a root is freed.
GNU R’s roots are listed in RunGenCollect in memory.c. The main ones follow.
The symbol table is a root. Every symbol must live forever. Code can look up the symbol by name at any time. The global environment is a root. User-defined variables in the top level live there. The base environment is a root. Built-in functions and constants live there.
The PROTECT stack is a root for C extensions. When C code allocates a SEXP, the object is not yet referenced from any other SEXP. It is invisible to the collector. The code calls PROTECT to push a pointer onto a stack. The collector scans this stack during marking. When the C code finishes, it calls UNPROTECT to pop the pointer. This tells the collector the object can become unreachable.
Active call contexts are roots. When R evaluates a function call, it creates a context on the C stack. That context holds the call, the function’s environment, the promises for its arguments and its on.exit code, and the collector traces these for every context on the stack. The byte-code interpreter’s value stack is a root too.
Registered roots are another. External C code keeps an object alive across calls with R_PreserveObject(), which adds the object to a precious list that the collector treats as a root. When the object is no longer needed, R_ReleaseObject() removes it. This is distinct from PROTECT, which is for temporaries within a single C call.
6.9.4 The PROTECT discipline
The PROTECT and UNPROTECT mechanism is a source of bugs. Consider this C code.
SEXP result = allocVector(INTSXP, 10);
SEXP list = allocVector(VECSXP, 2);
SET_VECTOR_ELT(list, 0, result);
SET_VECTOR_ELT(list, 1, result);
return list;The first line allocates an integer vector that nothing roots. The second line allocates again, and any allocation can start a collection. If one runs there, the vector is unreachable and is freed, and the third line stores a dangling pointer into the list. Nothing fails at that point; the crash, if one comes, comes later, when something reads the freed memory. Protecting each result before the next allocation fixes it.
SEXP result = allocVector(INTSXP, 10);
PROTECT(result);
SEXP list = allocVector(VECSXP, 2);
PROTECT(list);
SET_VECTOR_ELT(list, 0, result);
SET_VECTOR_ELT(list, 1, result);
UNPROTECT(2);
return list;Now both objects are on the protect stack while the next allocation runs. The pattern is tedious and easy to get wrong, and it leads to bugs in real packages.
The classic mistake is an unbalanced count. An early return that skips UNPROTECT, or an UNPROTECT(n) with the wrong n, leaves the stack at the wrong height. An error() does no harm here, because the jump resets the protect stack to the height saved in the target context; a plain return gets no such reset. And because the protect stack is a stack, UNPROTECT(1) pops whatever is on top, which is not necessarily the object the programmer meant. The AST evaluator checks the height around calls to builtins such as .Call and prints Warning: stack imbalance in '.Call', m then n when it changed. Byte-compiled code, which is how a package’s R functions run after installation, makes no such check at the .Call itself, so the warning names an enclosing builtin or never appears, and the damage can surface as a crash much later.
6.9.5 Observable behavior
The user can observe garbage collection in several ways. The gc() function forces a collection immediately. It returns a matrix whose rows are Ncells (cons cells) and Vcells (vector cells), and whose columns report cells used, megabytes used, the trigger level for automatic collection, megabytes at trigger, maximum used since last reset, and megabytes at maximum. When the vector heap has a limit, a limit (Mb) column appears after the trigger columns; macOS sets such a limit by default.
The gcinfo() function controls verbose output. After gcinfo(TRUE), R prints a few lines at each automatic collection: its number, how many collections of each level have run, its level, and how full the cons-cell and vector heaps are, for example Garbage collection 12 = 8+1+3 (level 1) ... followed by 31.2 Mbytes of cons cells used (83%). It prints no timing. Collection runs the same either way; gcinfo() controls only the output.
The collector runs automatically, when an allocation finds no free node or would take the vector heap past its current limit, the “gc trigger” column of gc(). After each full collection R resizes both limits from how full the heaps are (AdjustHeapSize in memory.c).
6.9.6 Concurrency coupling: a hard constraint
In a multithreaded runtime that shares one heap, garbage collection couples everything.
Mark bits live inside every SEXPREC. When the collector marks an object, it mutates a bit inside the object. Two interpreters cannot mark the same object at the same time. They corrupt the mark bit.
Generation list pointers also live inside every SEXPREC, so each node records which generation list it is on. When an object survives a collection, the collector unlinks it from its current list and links it into the next generation. Two collectors cannot modify these pointers concurrently without a mutex.
A collector must acquire locks to touch any SEXP. The more locks, the more contention. Per-object locks are out of the question. Every collection touches millions of objects. A single interpreter-wide lock is simpler. But that lock serializes all collection activity. If two interpreters run simultaneously, one must wait while the other collects.
Every SEXPREC embeds GC bookkeeping that mutates on every marking step. Independent collectors cannot share the same heap without coordination.
6.9.7 GNU R’s collector
Every collection has a level. Level 0 collects only the new generation, level 1 the new generation and old generation 0, and level 2 everything. After 20 level-0 collections the next one is level 1, after 5 level-1 collections the next is level 2, and a collection that leaves less than 20 percent of either heap free makes the next one a level higher. gc() called from R runs level 2 by default; gc(full = FALSE) runs whatever level the schedule says is next.
Marking comes first. Interrupts are suspended for the whole collection. The collector clears the mark bit on every node of the old generations it is collecting and puts those nodes back on the new lists. Old generations it is not collecting keep their bits and are not traced, except for the children of nodes on their old-to-new lists. It then marks from the roots. Marking does not recurse on the C stack: each newly marked node is put on a list of forwarded nodes, and a loop takes nodes off that list and marks their children until the list is empty.
Promotion happens during marking. A reachable new node goes onto the list of old generation 0, and a reachable node of old generation 0, when that generation is being collected, onto old generation 1.
Whatever is still on the new lists afterwards is garbage. Small nodes become the free lists for the next allocations, large vectors go back to the C allocator, and pages left with no live nodes can be released.
After a full collection, R also resizes the heaps. It recalculates the trigger for each heap from how full it is, growing it when occupancy is high and shrinking it when occupancy is low.
The collector is stop-the-world. When collection starts, all user code stops, and it resumes only when the collector finishes. For a single-threaded interpreter, this is fine: a level-0 collection is short, and a full collection traces the whole live heap, so its pause grows with it. For a multithreaded interpreter, a stop-the-world pause stops every thread that shares the heap. That is global synchronization, and it is hard to avoid.
6.9.8 Write barrier and generational correctness
A generational collector must handle this scenario. An old object holds a pointer to a young object. A young-only collection scans only young objects. It will not reach the old object, so the young object is never marked and is freed, and the old object is left holding a dangling pointer.
A write barrier prevents this. Every store into a SEXPREC field checks the generations of the two objects. If an old object receives a pointer to a younger one, the barrier records it in a remembered set. In GNU R that set is a list per generation: the barrier moves the old node onto its generation’s old-to-new list (old_to_new in memory.c). A collection that skips that generation traces the children of every node on its old-to-new list as if they were roots.
In GNU R the barrier lives in the setter functions in memory.c: SETCAR, SET_VECTOR_ELT, SET_STRING_ELT, SET_ATTRIB and the rest. R Internals notes that this is why SET_VECTOR_ELT and SET_STRING_ELT are functions and not macros. The documented API has no other way to store a SEXP into an object. R 4.6.1 still exports two writable pointers that bypass the barrier, STRING_PTR and DATAPTR, outside the API and kept for a few named packages. The check itself is a few loads and comparisons; only an old-to-new store pays for moving the node between lists. The same setters also update the reference counts.
6.9.9 GC and concurrency in other runtimes
Python uses reference counting plus cycle detection. Every object embeds a reference count and the runtime detects reference cycles. Reference counting is incremental, so most pauses are short, though the cycle detector still has to run. Every pointer write updates a count, and with several threads those updates must not race. The traditional implementation keeps plain, non-atomic updates safe with a global interpreter lock that serializes Python bytecode execution. C extensions can release that lock around work that does not touch Python objects. The free-threaded build (PEP 703) removes the global lock and changes the reference counting scheme itself to make concurrent updates safe.
HotSpot’s collectors are generational like R’s, but its young generation is collected by copying survivors out, not by marking in place, and its modern collectors were built for many threads from the start. G1 and ZGC do most of their marking concurrently with user code, which shortens pauses at the price of barriers. G1 uses write barriers and snapshot-at-the-beginning marking. ZGC uses load barriers on reference loads. Every store or load pays something, and how much depends on the collector.
Erlang (BEAM) uses a different strategy. Each Erlang process has its own heap and its own collector, and when a process sends a message to another, the message is copied. Large binaries, over 64 bytes, are the exception: they live in a shared, reference-counted area, and messages carry references to them. Every process collects its heap independently, so there is no global pause. The cost is memory duplication and copy overhead.
GNU R runs one interpreter per process. Garbage collection is stop-the-world. All user code pauses while collection runs.
6.9.10 threaded-r: per-interpreter heaps and immortal objects
In the threaded-r fork of GNU R, multiple interpreters run in the same process. Each interpreter has its own execution context, symbol table, and base environment. Heap ownership work has landed since I first wrote this page: each interpreter now owns its own generational rings and collects them without touching another interpreter’s.
As of 2026-08-25, each threaded-r interpreter owns its generational heap rings, and the symbol table and string cache are per-interpreter. The A/B/C churn gate passes: nodes from one interpreter’s rings found in the main heap measure zero, against a baseline of 814 to 6,432 per run. It was verified twice, under ASan and LSan, and with the ownership oracle set to abort on the first violation.
Isolation is not complete, and the project’s own risk register says so. The collector’s tuning parameters stayed process-global when the heap did not: an audit of memory.c moved twelve symbols out of the per-interpreter struct, including the growth fractions and vsfac. As of the same date, locale is still process-global, the graphics device table is shared behind a lock, and a package’s shared library is loaded once per process, so its C globals are shared.
threaded-r uses an immortal arena for builtin constants. An arena is a block of memory managed separately from the heap. It holds a small fixed set of builtin constants, among them R_NilValue (NULL), NA_STRING and the empty string, each with its mark bit permanently set. These constants are allocated once at startup and never freed. Every interpreter references them without GC coordination. This is analogous to CPython’s PEP 683 immortal objects.
Per-interpreter heaps eliminate most cross-interpreter collection coupling. Global synchronization drops from every collection to only when objects cross heap boundaries.
6.9.11 sunlight: fork, copy-on-write, and first-GC privatization
sunlight is an R package that uses the fork() system call to create workers. Fork creates a child process with a complete copy of the parent’s memory. In principle, this is cheap. With copy-on-write, the kernel marks the pages as shared at first, and when the parent or the child writes to a page, the kernel copies it to make it private. Only pages that are written get duplicated.
In practice, a full collection in the child breaks this promise. It clears the mark bit on every object in the old generations, then sets it again on every object it reaches, and it rewrites list links as it moves nodes between generation lists. Each of these is a tiny write, but the kernel copies the whole page for it. A 4 KB page holds about 73 of the 56-byte nodes R uses for pairlists, environments and other non-vector objects, so one write privatizes the page for all of them. A level-0 collection writes much less, only to new objects and the old-to-new lists, but new objects are allocated in the same pages as old ones, so it is not free either.
flowchart LR parent["parent heap<br/>pages"] -->|fork| child["child: pages shared<br/>copy-on-write"] child -->|first GC writes<br/>mark bits| priv["nearly every page<br/>privatized"]
Fork creates a child with shared memory. The child’s first full garbage collection writes mark bits into every reachable object, which copies the pages that hold them.
In its Day 7 benchmark of 2026-08-01, sunlight’s aggregate PSS came out only 1.28x below the best incumbent’s aggregate RSS at 8 workers and 1.10x below at 32. PSS splits each shared page among the processes that map it, and RSS counts it in full for each one, so the comparison itself favors sunlight. That was one run on WSL2, and crew is left out because it did not start all its workers. Workers that kept sharing the template’s heap would have opened a far wider gap. The project’s benchmark vignette attributes the gap to the collector, and it measured the effect in plain R: one gc() in a forked child privatized most of what the child had inherited.
sunlight workers are forked from a prewarmed template. A full collection in a child, which gc() runs by default, writes the header of every inherited object and so privatizes nearly every page that holds R objects.
Whether a different heap layout would keep those pages shared is open. A collector that kept mark bits in a side table, outside the objects, would not write to inherited pages when it marked them, but R’s reference counts and its generation list links live in the same headers.
6.9.12 Observable patterns in real code
Most R users never debug a garbage collection issue, and collections run silently. A few patterns show up anyway.
If gc() reports a “max used” far above “used”, the program built large temporary objects at some point. Rprof(memory.profiling = TRUE) and tracemem() can show where.
The protect stack can overflow. Its size is fixed at startup, 50,000 entries by default and set with --max-ppsize, and the usual cause is a loop that calls PROTECT on every iteration without a matching UNPROTECT. R stops with “protect(): protection stack overflow”.
6.9.13 Open questions
How must per-interpreter garbage collection be designed so that shared constants and builtin functions are not duplicated? The immortal arena is a partial solution. A better design can use a separate immutable-object heap.
If R uses a read barrier instead of a write barrier, can concurrent marking be implemented without stop-the-world pauses? The cost is lower throughput on every memory read.
Further reading
R Internals, Section 1.7, “The write barrier and the garbage collector”: https://cran.r-project.org/doc/manuals/r-release/R-ints.html#The-write-barrier
Writing R Extensions, Section 5.9.1, “Handling the effects of garbage collection”, on PROTECT: https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Garbage-Collection
Jones, R., Hosking, A., and Moss, E., The Garbage Collection Handbook: The Art of Automatic Memory Management. Chapman and Hall, 2011: https://gchandbook.org/
PEP 683, “Immortal Objects, Using a Fixed Refcount”: https://peps.python.org/pep-0683/
Where this appears
- threaded-r Every SEXPREC embeds GC bookkeeping. Per-interpreter heaps can remove most cross-interpreter synchronization.
- r-in-rust (rrs) A from-scratch design can isolate heaps completely. Each interpreter owns its collector, symbol table, and string cache.
- sunlight Fork copy-on-write saves little memory. A full collection in the child writes the header of every object it inherited.