flowchart TD
subgraph cstack["C Stack"]
cf1["frame: eval<br/>f(g(1:10))"]
cf2["frame: applyClosure<br/>function f"]
cf3["frame: applyClosure<br/>function g"]
cf1 --> cf2
cf2 --> cf3
end
subgraph rctx["R Context Stack"]
rc1["context: f call<br/>on.exit: none"]
rc2["context: g call<br/>on.exit: none"]
rc1 --> rc2
end
subgraph heap["Heap"]
envf["f's env: x<br/>parent: global"]
envg["g's env: n<br/>parent: global"]
vec1["integer vector<br/>1..10"]
end
cf2 -.-> rc1
cf3 -.-> rc2
rc1 -.-> envf
rc2 -.-> envg
envg -.-> vec1
5.1 Stack vs Heap
Every program divides its memory into two regions that behave differently. The stack holds data with known lifetime. The heap holds data with unknown lifetime. Understanding this division explains allocation costs, garbage collection pressure, and why threads complicate memory management.
5.1.1 Mental model
Think of the stack as a stack of plates. When a function runs, it pushes a new plate on top. The data for that function sits in its plate frame. When the function returns, its plate pops off. Allocation is cheap, just a pointer bump. Deallocation is free, just a pop.
The heap is a warehouse. Objects live indefinitely in scattered bins. The allocator tracks which bins are free. When you need storage, you ask the allocator for a bin. When you no longer need it, you return it. Finding a free bin takes time. Fragmentation happens: bins scatter across the warehouse, making storage less efficient.
The stack works because lifetimes follow a predictable order. You enter a function, exit it, then never use that frame again. The heap works because lifetimes are arbitrary. An object created in one function can outlive that function and be used in another.
5.1.2 Mechanism
The stack
A thread owns one stack. The stack is contiguous memory that grows as you enter functions and shrinks as you exit. The hardware maintains a stack pointer register. When you call a function, the call instruction pushes the return address and the called function reserves a frame, a contiguous block on the stack. The frame holds the function’s local variables, return address, and saved registers.
Each frame stores return address information. The function prologue adjusts the stack pointer and saves the old frame pointer. The function body uses the frame. The function epilogue restores the frame pointer and stack pointer, then jumps to the return address.
Allocation on the stack is a single instruction. The stack pointer decrements by the frame size, then the memory is valid. Deallocation is also one instruction. The stack pointer increments back, and the memory is discarded. Neither operation calls an allocator.
The stack has a fixed maximum size, which the operating system reserves when the thread starts, with a guard page past the end. If code pushes too many frames, the stack runs into the guard page, the hardware raises a fault, and the operating system ends the program: a segmentation fault on Linux and macOS, a stack overflow exception on Windows. This is stack overflow.
The heap
All threads in a process share the heap. An allocator manages it: the C library’s malloc, or a replacement such as jemalloc or mimalloc. The basic pattern is the same in each. The allocator tracks which memory blocks are free. When you request N bytes, it finds a free block of at least N bytes, marks it as used, and returns the address. When you release it, it marks the block as free, and many allocators merge it with free neighbors.
A simple allocator keeps one free list and searches it, which costs time proportional to the number of free blocks. Production allocators avoid most of that search by keeping a separate free list for each size class, so a typical request takes the first block from the right list.
The heap allows any lifetime. An object allocated in function A can be passed to function B, stored in function C, and deallocated in function D. The heap does not enforce any ordering.
Fragmentation occurs when free blocks scatter across memory. If you allocate many small objects and deallocate most, then request one large contiguous block, you cannot find it. This happens despite sufficient total free memory. A C allocator cannot close the gaps by moving live blocks, because it does not know where the pointers to them are. Only a runtime that knows every pointer, such as one with a moving garbage collector, can compact its heap. R’s collector does not move objects.
Address space layout
In R, the two regions hold different things:
Each thread’s stack holds one frame per active call. The heap holds objects of any lifetime, shared by all threads, and a local in a frame points into it.
In the classic layout of a single-threaded Linux process, the lowest addresses hold code and global data, the heap starts above them and grows upward, and the stack starts near the top of the address space and grows downward. Real processes are messier: each extra thread gets its own stack elsewhere in the address space, large allocations come from separate mapped regions, and address-space randomization moves all of these on every run.
Stack or heap, object by object
In C, the compiler decides placement.
Local variables declared in function scope live on the stack. They have automatic storage duration. When the function returns, the stack frame pops, and the locals vanish. You cannot return a pointer to a local variable, because that local no longer exists after the return.
int* get_pointer() {
int x = 42;
return &x; // danger: x dies when function returns
}Objects allocated with malloc live on the heap. They have dynamic storage duration. You must explicitly free them. They outlive the function that allocated them. You can return a pointer to a heap object safely.
#include <stdlib.h>
int* get_heap_value() {
int* p = malloc(sizeof(int));
*p = 42;
return p; // safe: object persists on heap
}Global variables live in the data segment below the stack, never on the heap or stack. They exist for the entire program.
In Rust, the ownership model makes the choice explicit.
Local variables bind to ownership. If the binding is a small type like an integer, the value itself sits on the stack. When the variable goes out of scope, the stack slot is reclaimed. If the binding is a Box, Vec, or String, the value lives on the heap, and the local variable holds a pointer to it. When ownership moves, the pointer moves too. The heap memory stays allocated until its owner goes out of scope, and a Box or Vec has exactly one owner. Then a destructor runs and frees it.
let x = 42; // x on stack
let v = vec![1, 2]; // v on stack, vector data on heap
let b = Box::new(x); // b on stack, x's copy on heapAssigning or passing a value moves it, unless its type implements Copy. Size does not decide this. Integers, floats, bool and char are Copy, and so are arrays and tuples built from them, however large. Box, Vec and String own heap memory, so they cannot be Copy and they move. This forces you to think about when heap allocation happens and who owns the data.
In R, every object lives on the heap, and code reaches it through a SEXP pointer.
GNU R allocates every user-visible object on the heap: integers, reals, strings, environments, functions, and lists. C code refers to an object through a SEXP, a pointer to its SEXPREC node. The pointers themselves sit in C local variables on the C stack, in the PROTECT stack, and in the byte-code interpreter’s node stack. InitMemory in memory.c allocates those last two arrays with malloc, so they live on the C heap, not on the C stack.
The C stack holds the frames of the evaluator’s C functions, such as eval, applyClosure and bcEval. When R checks the C stack and finds it nearly full, it stops with “C stack usage N is too close to the limit”. That message is about the C stack, not the R heap.
R also keeps a context stack. Each closure call opens a context, an RCNTXT struct that records the call, the function, its environment, the promised arguments, any on.exit code, and a jmp_buf that lets an error or return() jump back to that point. The RCNTXT is a local variable of the C function that opened it, so the context stack is a linked list running through the C stack, headed by R_GlobalContext. Error handling and sys.call() walk this list.
Escape analysis
Compilers for garbage-collected languages use escape analysis to keep some objects off the heap. The compiler proves that an object’s lifetime does not escape the function. If the object never leaks a pointer to another scope, the compiler allocates it on the stack instead of the heap.
An object escapes if a pointer to it is returned or stored outside the function scope. It escapes if passed to an unknown function or stored in an object that escapes. If it does not escape, the compiler allocates it on the stack and deallocates it when the function returns. Stack allocation is cheaper than heap allocation.
A plain interpreter does no such analysis. It runs each operation when it reaches it and never looks ahead to prove that an object stays local, so every object goes on the heap. JIT compilers such as HotSpot’s C2 and PyPy’s do run escape analysis on hot code. The missing analysis is one reason interpreted languages allocate more than compiled ones.
5.1.3 Internal mechanics
Stack frames in detail
When a CPU executes a function call, the call instruction pushes the return address. The function prologue then pushes the old frame pointer, adjusts the stack pointer, and allocates space for locals. When the compiler keeps frame pointers, the saved frame pointers and return addresses form a linked list. Walking it reconstructs the call stack, which is how a debugger prints a stack trace (or it reads unwind tables, when the frame pointers were left out).
The stack pointer is the only state mutation needed. Allocation bumps the pointer. Deallocation moves it back. No data structure tracks what is allocated. The pointer’s position encodes it.
Return address information on the stack enables attacks. Stack buffer overflows write past the end of a local array, clobbering the return address. The attacker then redirects the CPU to malicious code. Compilers insert stack canaries to detect this, and recent x86 CPUs add a hardware shadow stack (part of Intel CET) that keeps a second copy of each return address.
Heap allocation strategies
Allocators implement different strategies. The bump allocator is the simplest: it maintains a pointer to the next free byte. Allocation advances the pointer and returns the old position. When an object dies, nothing happens. Deallocation is a no-op. The entire arena is freed only when all objects in it die.
Most programs need deallocation during execution. A free list allocator tracks free blocks in a linked list. Allocation searches the list for a block of the required size. Deallocation inserts the block back into the list, possibly merging with adjacent free blocks.
Buddy allocation splits the heap into power-of-two sized blocks. Allocation rounds up the request size to the next power of two and finds a free block. Deallocation marks the block as free and recursively merges with its buddy if the buddy is also free. This limits fragmentation.
Generation-based allocation separates young and old objects. Young objects are allocated in a small nursery and freed often. Old objects survive collection and are rarely freed. This reduces the cost of allocation and collection for young objects, the common case.
Garbage collection and allocation rate
When the allocator runs out of free memory, execution pauses for garbage collection. The garbage collector marks live objects and frees the dead ones. The time paused depends on the number of live objects and the complexity of the marking algorithm.
High allocation rate amplifies GC pressure. If code allocates many temporary objects, the heap fills quickly. Collection runs frequently. In R, this happens often. R code that builds temporary data structures allocates aggressively. Many intermediate results are new heap objects, though arithmetic reuses a temporary operand’s storage when nothing else refers to it. Each closure call also allocates on the heap, a new environment and a promise for each argument that is not a constant, so a recursive function allocates at every level.
Garbage collection has its own page. What matters here is that allocation pattern drives collection frequency. Code that allocates little rarely triggers a collection. Code that allocates in a tight loop triggers them constantly, and pays for every one.
5.1.4 Threads and memory
Each thread receives its own stack when the operating system creates it. The stacks are independent. All threads share one address space, so nothing in the hardware stops one thread from reading another thread’s stack through a pointer, but a local stays private unless code hands its address to another thread. That privacy is cheap and needs no synchronization.
The heap is shared. All threads in a process access the same heap. Allocating from the heap requires synchronization if multiple threads allocate concurrently, because two threads changing one free list at once is a data race. Allocators use locks for this, and modern ones also give each thread its own cache or arena, so most allocations take no lock at all.
Shared memory in the heap is a source of complexity. Objects on the heap can be reached from multiple threads. If one thread mutates an object while another reads it, behavior is undefined. The program must enforce mutual exclusion. This is why threaded programs require locks or atomic operations.
Allocation rate also couples threads through the collector. With one shared heap and a stop-the-world collector, one thread’s allocation can trigger a collection that pauses every thread. GNU R does not meet this today, because it runs R code on one thread only. It becomes the problem as soon as several interpreters share one heap.
5.1.5 Other systems
C gives the programmer control. Local variables go on the stack. malloc chooses the heap. The programmer must avoid dangling pointers and memory leaks.
C++ adds RAII (Resource Acquisition Is Initialization). Objects constructed on the stack are destroyed when they go out of scope. This ensures cleanup. Smart pointers like unique_ptr and shared_ptr manage heap objects automatically.
In Java’s model every object lives on the heap, although HotSpot’s JIT can remove the allocation for objects that do not escape. Local variables of primitive type, and the references themselves, live in the stack frame. The garbage collector frees unreachable objects automatically, and programmers never deallocate manually. The trade-off is that collection pauses come when the collector decides, not when the program does.
Go decides placement with escape analysis. A local that the compiler can prove is not referenced after its function returns stays in the stack frame. Anything else, and anything very large, goes on the garbage-collected heap. Goroutines each have a stack that grows dynamically.
Rust requires explicit ownership. Local variables own their values. If the value lives on the heap, the local owns the heap memory. When the local goes out of scope, the heap memory is freed. Move semantics transfer ownership. Borrowing allows temporary access without ownership transfer. The compiler enforces these rules at compile time, so runtime checks are not needed.
5.1.6 R’s approach
GNU R runs one interpreter per process. Every R object lives on the heap, and the interpreter allocates constantly. When the count of nodes in use reaches its current limit, or the vector heap would pass its own, the allocator (allocVector for vectors) runs the collector first. All R code stops while the collector marks live objects and frees dead ones, then the allocation goes ahead.
Deep recursion in R runs out of a stack, not out of heap. Each R call adds frames to the C stack and entries to R’s own stacks, and R checks four limits: the expressions option (5000 nested evaluations by default), the byte-code node stack, the PROTECT stack, and the C stack. In R 4.6.1 on Windows, f <- function(n) if (n <= 0) 0 else n + f(n - 1) fails just under depth 5000 with “evaluation nested too deeply: infinite recursion / options(expressions=)?”. With the option raised it fails at the node stack instead, with “node stack overflow”. The objects on the heap are intact, but the evaluation cannot continue.
The threaded-r project runs several interpreters in one process and gives each one its own heap, so each interpreter’s collector works on its own objects. Its churn gate, which destroys interpreters while another keeps allocating, finds none of an interpreter’s nodes living in the main heap. The design decision was to patch GNU R instead of rewriting it, which limits the scope of changes.
In r-in-rust, each interpreter owns one heap and its own collector, and only the thread that owns the interpreter allocates from it, so heap allocation needs no lock. The cost is that an R value cannot pass between interpreters without a copy.
Consider evaluating f(g(1:10)) in R. The expression creates nested calls. The C stack grows. Each R function creates a context. Each vector allocation goes on the heap.
C stack frames belong to the interpreter’s own C functions, R contexts track each closure call, and heap objects hold the data. Pointers connect the layers.
When g returns, its context pops from the R context stack. Its local bindings become unreachable. The value it returned stays on the heap, reachable from f’s environment through the promise bound to x. When f returns, that context pops. The value stays on the heap until the garbage collector determines it is unreachable.
5.1.7 Relevance to my work
Understanding stack and heap explains several constraints.
Stack limits, not heap size, cap the depth of recursion in R, so giving R a larger heap does not help. Raising options(expressions = ) moves only the first limit. The node stack’s size is fixed when R is built, and the C stack’s size comes from the operating system (ulimit -s before starting R, on Linux and macOS). The fixes that hold are to rewrite the algorithm as a loop or, since R 4.4.0, to make the recursive call through the experimental Tailcall(), which reuses the current call’s context.
Heap allocation rate drives garbage collection frequency. When R code allocates aggressively, collection pauses increase. Reducing allocation (by reusing vectors instead of creating new ones, for example) reduces GC time.
In threaded-r, one heap shared by several interpreters would let one interpreter’s allocation pause all of them. Per-interpreter heaps keep each interpreter’s allocation and collection on its own thread.
In r-in-rust, every interpreter owns its heap. No synchronization is needed for heap allocation, and the interpreter can allocate without waiting for other threads.
Further reading
- “Operating Systems: Three Easy Pieces” (OSTEP), chapter “The Abstraction: Address Spaces”: https://pages.cs.wisc.edu/~remzi/OSTEP/vm-intro.pdf
- OSTEP, chapter “Free-Space Management”: https://pages.cs.wisc.edu/~remzi/OSTEP/vm-freespace.pdf
- Rust Book, chapter 4.1, “What Is Ownership?”: https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html
- “R Internals”, section 1.4, “Contexts”: https://cran.r-project.org/doc/manuals/r-release/R-ints.html#Contexts
- “Writing R Extensions”, section 6.15, “C stack checking”: https://cran.r-project.org/doc/manuals/r-release/R-exts.html#C-stack-checking
Where this appears
- threaded-r Understanding heap allocation patterns explains why R performance degrades under recursion and why per-interpreter heaps reduce GC coupling.
- r-in-rust (rrs) Rust’s ownership model makes stack vs heap choice explicit. The design requires understanding both layers.