Programming Search⌘K

Conceptcore

Stack and heap

Also called call stack and heap, call stack, stack frame, activation record, automatic storage, stack allocation, heap allocation, dynamic storage, escape analysis.

Each active function call keeps its locals in a frame on the stack, which goes away at the return. Data that must outlive the call goes on the heap, where an allocator finds room for it.

Applies to
core-languages

Idea

A running program needs memory for two kinds of data. Some data belongs to one call of a function: its arguments, its local variables, and the place to go back to when the call ends. This data lives exactly as long as the call. Other data must outlive the call that makes it. Examples are a record that a function builds and returns, a list that grows while the program runs, and a buffer that another thread reads. Most language implementations keep the first kind on the call stack and the second kind on the heap.

The stack is a region of memory that grows and shrinks at one end only. Each call adds a frame at the top, and each return removes the frame at the top. The heap is a pool of memory that an allocator manages. The program asks for a block of some size and uses it as long as it needs. The block comes back later, by an explicit release or through a garbage collector. The two differ in lifetime, in cost, and in who decides when the memory comes back.

In CPython every value is an object in a private heap, and a frame holds only references to objects.2122 In this run, make_order builds a dictionary and returns it. The frame of the call goes away at the return, but the dictionary stays, because it was never in the frame.

import inspect


def frames_below():
    return len(inspect.stack()) - 1


def make_order(item):
    order = {"item": item, "frames": frames_below()}
    return order


order = make_order("book")
print(order)
print("frames at module level:", frames_below())
Output
{'item': 'book', 'frames': 2}
frames at module level: 1

frames_below counts the frames under its own call. Inside make_order there are two (the call of make_order and the module), and at module level there is one.

How it works

The call stack. Each thread has a stack of its own.8 The Rust book describes the order: "The stack stores values in the order it gets them and removes the values in the opposite order."32 A register, the stack pointer, holds the address of the top. A call moves the stack pointer to make room for a frame, and the return moves it back. Dijkstra described this scheme in 1960. A block of storage holds the stack, and the stack pointer points to the first free place in it.1 A frame usually holds these items:

  • the return address, the place in the caller where execution goes on after the call;
  • the registers of the caller that the called function must save before it uses them;
  • the local variables of the call;
  • the arguments that the calling convention does not pass in registers, and room for temporary values.

The calling convention of the platform fixes the exact layout. The diagram shows a program in the middle of a call of total from main.

stack                                         heap

+-------------------------------+
| frame of main                 |
|   return address (into start) |
|   order  -------------------------------->  Order { id: 7, items: ---> }
+-------------------------------+                                    |
| frame of total(order)         |                                    v
|   return address (into main)  |                         [ "book", "pen" ]
|   saved registers             |
|   sum = 0                     |
+-------------------------------+  <- stack pointer (the top)

Frames come and go in last-in, first-out order, so the lifetime of each frame lies inside the lifetime of its caller's frame. A function can pass the address of a local variable to the functions that it calls. It cannot use that address after it returns, because the next call reuses the same memory. A recursive call gets a frame of its own, so each level has its own copy of the locals. The C standard says this directly: a block that is entered recursively gets a separate instance of each of its automatic objects.3

The heap. Heap blocks have no such order. The allocator keeps track of the free parts of the heap. For each request it finds a free block that is large enough, marks it as used, and returns its address. A release marks the block as free again. The block lives from the allocation until the release, no matter which functions do them.35 MDN calls the heap of a JavaScript engine "just a name to denote a large (mostly unstructured) region of memory".33 The word names a pool of memory here, not the heap data structure. The internals of allocators, such as free lists and size classes, are on Manual memory management. The pseudocode puts the two side by side.

  1. CALL f(arguments)
  2. 1put the arguments in registers or on the stack
  3. 2push the return address
  4. 3sp ← sp − framesize(f) ▷ room for saved registers and locals
  5. 4run the body of f
  6. RETURN
  7. 5sp ← sp + framesize(f) ▷ the locals of f are gone
  8. 6pop the return address and jump to it
  9. ALLOCATE(n) ▷ the heap
  10. 7find a free block b with size(b) ≥ n
  11. 8mark b as used and return its address
  12. RELEASE(b)
  13. 9mark b as free ▷ by the program, the owner, or a collector

Who decides where a value lives. Languages split into three groups.

  • In C, C++, Rust and C#, the program says it. C has automatic storage for locals and allocated storage for malloc blocks, and its standard never uses the words stack or heap.3 C++ calls the second kind dynamic storage, which new and delete manage.45 Rust keeps values in the frame unless the program puts them in a Box, a Vec or another owner of a heap block.30 In C#, a variable of a value type holds an instance of the type. A variable of a class type holds a reference to an instance.25 Boxing stores a value type on the managed heap.26
  • In Go and Java, the compiler decides. The Go FAQ says that the program does not need to know: each variable exists as long as there are references to it. The compiler keeps a local in the frame when it can prove that no reference outlives the call. Otherwise it moves the local to the garbage-collected heap.12 The compiler flag -m prints these decisions.18 For newOrder in the Go example, go build -gcflags=-m reports moved to heap: o. The Java Virtual Machine allocates every class instance and array on the heap.8 The HotSpot compiler runs escape analysis and can remove the allocation of an object that does not escape. It does not move such an object to the stack.9
  • In Python and JavaScript, the program has no say. Objects live on the heap of the runtime, and the engine manages the frames.

In the managed languages the place is a detail of the implementation. Eric Lippert argued that it is the wrong thing to teach about C# value types: "Surely the most relevant fact about value types is not the implementation detail of how they are allocated". What matters is that they are always copied by value.34

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin/JVM uses the frames and the heap of the JVM, as in the Java example, and deep recursion throws StackOverflowError; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query has no frames or heap objects of its own; the database engine manages its memory.
BashDoes not applyBash has a stack of function calls with local variables, but every value is a string that the shell stores, and a script has no say in where.
PowerShellNativePowerShell runs on .NET, so its values are .NET value types or objects on the managed heap, as in the C# example; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no storage.
CSSDoes not applyStyle rules have no storage.
Regular expressionsDoes not applyA pattern has no storage.

Every example file shows the two places. It shows a value whose lifetime is one call and a value that outlives the call. Some files also show the copy rules that follow from where a value lives. Several files also run into the stack limit.

Language Verdict How the language exposes the stack and the heap
Python native every value is an object on the heap; frames hold references; the interpreter limits the depth of the stack1921
JavaScript native objects on the heap of the engine; Node.js throws a RangeError when the stack is full
TypeScript native the runtime model of the JavaScript that it compiles to
Java native one stack of frames per thread; every object and array on the heap; primitives in locals; boxing makes objects811
C native automatic and allocated storage durations; malloc and free3
C++ native automatic and dynamic storage durations; new, delete, std::unique_ptr45
C# native value types (struct) are copied; class instances are reached through references; boxing; stackalloc and ref struct25262728
Go native the compiler picks the place by escape analysis; goroutine stacks grow1213
Rust native values in the frame by default; Box and Vec own heap blocks30
Kotlin native on the JVM, the model of Java
PowerShell native the model of .NET, as for C#
Bash n/a the shell stores every value as a string and the script has no say in where
SQL n/a a query has no frames or heap objects of its own
Regex n/a a pattern has no storage
HTML/CSS n/a markup and style rules have no storage

Values and boxed objects. Where a value lives also decides what an assignment copies. A Java int local holds the number, and assignment copies it. An array or any other object lives on the heap, and assignment copies only the reference. Boxing turns a primitive into an Integer or another wrapper object. The Java Language Specification notes that a boxing conversion can throw OutOfMemoryError when it must allocate a wrapper.11 C# has the same split between struct and class. Boxing a value type allocates an object on the heap and copies the value into it.26 Go and Rust treat structs as values that the program can copy, and a pointer or a Box is the way to share one. CPython has no unboxed values: an integer is an object, and the CPython id of an object is its address in memory.22

Managed runtimes. In Java, Kotlin, C#, PowerShell, Go and JavaScript, a garbage collector frees heap objects. A reference from a live frame keeps an object alive, because the locals of the active frames are roots of the collector (see Garbage collection). In C and C++ the program frees heap blocks itself. In Rust the owner of the block frees it at the end of its scope (see Ownership and borrowing).

PythonGitHub
import sys


def descend(level):
    return descend(level + 1)


print("recursion limit:", sys.getrecursionlimit())
try:
    descend(1)
except RecursionError as error:
    print("caught:", type(error).__name__)

print(isinstance(7, object), isinstance(descend, object))
Output
recursion limit: 1000
caught: RecursionError
True True
  • Verdict: native. CPython keeps every value, even an integer, as an object in its private heap, and a frame holds references to objects.
  • Each call of descend adds a frame. When the depth passes the limit that sys.getrecursionlimit() returns, the interpreter raises RecursionError, and the program can catch it.
  • The limit protects the C stack of the interpreter. sys.setrecursionlimit changes it, and a limit that is too high can crash the process.
#include <memory>
#include <print>
#include <string>

struct Buffer {
    explicit Buffer(std::string name) : name(std::move(name)) {
        std::println("acquire {}", this->name);
    }
    ~Buffer() { std::println("release {}", name); }
    std::string name;
};

int main() {
    {
        Buffer local("local");
        auto owned = std::make_unique<Buffer>("owned");
        std::println("end of block");
    }
    Buffer* raw = new Buffer("raw");
    delete raw;
}
Output
acquire local
acquire owned
end of block
release owned
release local
acquire raw
release raw
  • Verdict: native. local has automatic storage and its destructor runs at the end of the block. The object that std::make_unique makes has dynamic storage, and the std::unique_ptr deletes it at the end of the same block.
  • Objects in a block are destroyed in the reverse order of their construction, so owned goes before local.
  • new and delete manage dynamic storage by hand. Every new needs exactly one delete, which is why owning pointers such as std::unique_ptr exist. See Resource acquisition is initialization.
JavaGitHub
public class Main {
    static int deepest = 0;

    static void descend(int level) {
        deepest = level;
        descend(level + 1);
    }

    public static void main(String[] args) {
        try {
            descend(1);
        } catch (StackOverflowError error) {
            System.out.println("StackOverflowError after more than 1000 frames: " + (deepest > 1000));
        }

        int count = 5;
        int copy = count;
        copy++;
        System.out.println(count + " " + copy);

        int[] totals = {5};
        int[] alias = totals;
        alias[0]++;
        System.out.println(totals[0]);

        Object boxed = count;
        System.out.println(boxed.getClass().getName());
    }
}
Output
StackOverflowError after more than 1000 frames: true
5 6
6
java.lang.Integer
  • Verdict: native. Each thread has a stack of frames, and every object and array lives on the heap. A local of a primitive type such as int holds the value itself.
  • StackOverflowError is an error that the program can catch. The JVM throws it when a thread needs a larger stack than the limit, which -Xss sets.
  • Assigning an int copies the number. Assigning an array copies the reference, so alias and totals share one array.
  • Assigning an int to an Object boxes it into an Integer. HotSpot escape analysis can remove some allocations, but it never moves an object to the stack.
#include <stdio.h>
#include <stdlib.h>

int factorial(int n) {
    int result = 1; // each call has its own result
    if (n > 1) {
        result = n * factorial(n - 1);
    }
    return result;
}

int *make_totals(size_t count) {
    int *totals = malloc(count * sizeof *totals);
    if (totals != NULL) {
        for (size_t i = 0; i < count; i++) {
            totals[i] = (int)(i * 10);
        }
    }
    return totals;
}

int main(void) {
    printf("%d\n", factorial(5));
    int *totals = make_totals(3);
    if (totals == NULL) {
        return 1;
    }
    printf("%d %d %d\n", totals[0], totals[1], totals[2]);
    free(totals);
}
Output
120
0 10 20
  • Verdict: native. The C standard speaks of automatic and allocated storage durations, not of a stack and a heap.
  • Each call of factorial has its own result, because a recursive call makes a separate instance of each automatic object.
  • The block from malloc outlives make_totals. It lives until free, and the caller must call free exactly once. See Manual memory management.
  • Returning the address of a local is undefined behaviour. The Pitfalls section shows how AddressSanitizer finds it.
using System;

var a = new PointValue(1, 2);
var b = a;
b.X = 10;
Console.WriteLine($"struct: {a.X} {b.X}");

var c = new PointObject(1, 2);
var d = c;
d.X = 10;
Console.WriteLine($"class: {c.X} {d.X}");

object boxed = a;
a.X = 99;
Console.WriteLine($"boxed copy: {((PointValue)boxed).X}");

Span<int> totals = stackalloc int[3];
for (var i = 0; i < totals.Length; i++)
{
    totals[i] = i * 10;
}
Console.WriteLine(totals[2]);

struct PointValue(int x, int y)
{
    public int X = x;
    public int Y = y;
}

class PointObject(int x, int y)
{
    public int X = x;
    public int Y = y;
}
Output
struct: 1 10
class: 10 10
boxed copy: 1
20

This code does not compile, on purpose.

using System;

Console.WriteLine(Make()[0]);

static Span<int> Make()
{
    Span<int> buffer = stackalloc int[4];
    buffer[0] = 42;
    return buffer; // the frame and its memory end here
}
  • Verdict: native. A variable of a struct type holds the value, and assignment copies it. A variable of a class type holds a reference, so c and d are one object.
  • Converting a struct to object boxes it: the runtime allocates an object on the managed heap and copies the value into it. A later change to a does not reach the boxed copy.
  • stackalloc puts the array in the frame, and it goes away when the method returns. A Span<int> reads it safely.
  • A StackOverflowException cannot be caught. The process ends.
  • The compiler tracks the scope of each span, so the fails block, which returns a span over memory in a frame that is about to end, does not compile.
JavaScriptGitHub
let deepest = 0;

function descend(level) {
  deepest = level;
  descend(level + 1);
}

function makeUser(name) {
  const user = { name };
  return user;
}

try {
  descend(1);
} catch (error) {
  console.log(error instanceof RangeError, error.message);
  console.log("deeper than 1000 frames:", deepest > 1000);
}

const user = makeUser("alice");
console.log(user.name);
Output
true Maximum call stack size exceeded
deeper than 1000 frames: true
alice
  • Verdict: native. The engine keeps objects on its heap and manages the frames. The program cannot choose where a value lives.
  • Node.js throws a RangeError with the message "Maximum call stack size exceeded" when the stack is full. The program can catch it, and the frames above the catch are gone by then.
  • makeUser returns an object that it made in its own call. The object outlives the frame because only the reference was in the frame.
TypeScriptGitHub
interface Order {
  id: number;
  total: number;
}

function makeOrder(id: number): Order {
  const order: Order = { id, total: 0 };
  return order;
}

function countDown(n: number): number {
  return n === 0 ? 0 : 1 + countDown(n - 1);
}

const order = makeOrder(7);
const alias = order;
alias.total = 250;
console.log(order.id, order.total);

console.log(countDown(1000));
try {
  countDown(10_000_000);
} catch (error) {
  console.log(error instanceof RangeError);
}
Output
7 250
1000
true
  • Verdict: native. TypeScript compiles to JavaScript, so the stack and the heap are those of the JavaScript engine. The types do not change where a value lives.
  • alias and order refer to the same object on the heap, so a change through one name shows through the other.
  • A depth of 1000 calls fits in the stack. A depth of ten million does not, and Node.js throws a RangeError.
package main

import "fmt"

type order struct {
	id    int
	total int
}

func newOrder(id int) *order {
	o := order{id: id, total: 100}
	return &o
}

func depth(n int) int {
	if n == 0 {
		return 0
	}
	return 1 + depth(n-1)
}

func main() {
	p := newOrder(7)
	fmt.Println(p.id, p.total)
	fmt.Println(depth(1_000_000))
}
Output
7 100
1000000

This code fails on purpose. The output below is the error.

package main

import (
	"fmt"
	"runtime/debug"
)

func descend(level int) int {
	return descend(level+1) + 1
}

func main() {
	debug.SetMaxStack(1 << 20)
	fmt.Println(descend(1))
}
  • Verdict: native. The compiler decides where each variable lives. newOrder returns the address of a local, which is safe: go build -gcflags=-m reports moved to heap: o.
  • A goroutine stack starts small and grows when it needs to, so a recursion depth of one million works here.
  • The stack has a maximum, 1 GB on 64-bit systems by default. debug.SetMaxStack lowers it in the second block, and the runtime stops with fatal error: stack overflow and exit status 2.
RustGitHub
use std::mem::{size_of, size_of_val};

#[derive(Debug)]
enum List {
    Cons(i32, Box<List>),
    Nil,
}

fn main() {
    let buffer = [0u8; 1024];
    let boxed = Box::new([0u8; 1024]);
    println!("buffer in the frame: {} bytes", size_of_val(&buffer));
    println!("box in the frame is one pointer: {}", size_of_val(&boxed) == size_of::<usize>());
    println!("bytes behind the box: {}", size_of_val(&*boxed));

    let list = List::Cons(1, Box::new(List::Cons(2, Box::new(List::Nil))));
    println!("{list:?}");
}
Output
buffer in the frame: 1024 bytes
box in the frame is one pointer: true
bytes behind the box: 1024
Cons(1, Cons(2, Nil))

This code fails on purpose. The output below is the error.

fn descend(level: u64) -> u64 {
    if level == u64::MAX {
        return 0;
    }
    let buffer = std::hint::black_box([level; 64]);
    descend(level + 1) + buffer[0]
}

fn main() {
    println!("{}", descend(1));
}

This code does not compile, on purpose. The error is E0515.

fn largest(values: &[i32]) -> &i32 {
    let mut best = values[0];
    for &v in values {
        if v > best {
            best = v;
        }
    }
    &best // best lives in this frame
}

fn main() {
    println!("{}", largest(&[3, 9, 4]));
}
  • Verdict: native. A value lives in the frame of its owner by default. A Box, a Vec or another type that owns a heap block puts it on the heap.
  • The array buffer takes 1024 bytes in the frame. The Box takes one pointer in the frame, and its 1024 bytes are on the heap.
  • A recursive type needs a Box: without it, the size of List would have no limit.
  • A stack overflow is not a panic. The runtime prints that the thread has overflowed its stack and aborts the process. A thread from std::thread gets 2 MiB of stack by default.
  • The second fails block returns a reference to a local variable. The variable dies with the frame, so the borrow checker rejects the program with E0515. Return the value itself, or a reference into the argument.
  • Escape analysis. The compiler proves that no reference to an object outlives the function or the thread. Go then keeps the variable in the frame.12 HotSpot instead replaces the fields of an object that does not escape with plain locals ("scalar replacement") and drops the allocation. It also removes locks on objects that do not escape globally.9 The flag -XX:+DoEscapeAnalysis is on by default.10
  • Growable stacks. A Go goroutine starts with a stack of a few kilobytes. The runtime grows and shrinks it as the calls need.13 To grow it, the runtime copies the whole stack to a larger contiguous block.14
  • Stack-only types. C# stackalloc puts a block of memory in the frame. The block goes away when the method returns.28 A ref struct can never be boxed, stored in a class field, or captured by a lambda, so it can never reach the heap.27 C has variable length arrays: automatic objects whose size is known only at run time, which live until the program leaves their scope.3
  • Static storage. Global variables and C static locals live in a third place, for the whole run of the program.3
  • Closures. A function that captures a local of its enclosing function can outlive that function, so the captured variable cannot stay in the frame. Go moves it to the heap, as the Cost section shows. See Closure.
  • Threads. Each thread has its own stack, and all threads share the heap.8 So a value in a frame belongs to one thread, and an object on the heap needs synchronization when several threads use it. See Thread.
  • Pointers into the stack. A pointer to a local is valid only while the frame exists. Pointers and references covers the rules, and Use after free covers the bugs.

Pitfalls

Returning the address of a local

A C function that keeps the address of a local after it returns leaves a dangling pointer. The C standard makes any use of it undefined behaviour.3 Clang warns about a plain return &total; by default.7 It does not warn when the address goes through a global variable, as here. AddressSanitizer finds the read as a stack-use-after-return. The check is on by default on Linux, and the flag -fsanitize-address-use-after-return=always turns it on everywhere.6

This code has a memory error, on purpose, and the sanitizer reports it.

#include <stdio.h>

static int *last;

void make_total(int a, int b) {
    int total = a + b;
    last = &total; // the address outlives the frame
}

int main(void) {
    make_total(2, 3);
    printf("%d\n", *last);
}

Return the value itself, or put the value in a heap block whose lifetime the caller controls.

#include <stdio.h>
#include <stdlib.h>

int make_total(int a, int b) {
    return a + b;
}

int *make_total_on_heap(int a, int b) {
    int *total = malloc(sizeof *total);
    if (total != NULL) {
        *total = a + b;
    }
    return total;
}

int main(void) {
    printf("%d\n", make_total(2, 3));
    int *total = make_total_on_heap(2, 3);
    if (total == NULL) {
        return 1;
    }
    printf("%d\n", *total);
    free(total);
}
Output
5
5

Go needs no fix for the same code: the compiler moves the local to the heap.12 Rust and C# reject such a program at compile time. The Rust example returns a reference to a local, and the borrow checker stops it with E0515. The C# example returns a Span<int> over stackalloc memory, and the compiler stops it too.

Deep recursion overflows the stack

Each call takes a frame, so the depth of recursion is limited by the size of the stack. A recursive walk over a long linked structure fails long before the heap is full. CPython stops at a depth that sys.getrecursionlimit() returns, and raises RecursionError.1920

This code raises RecursionError, on purpose.

def length(node):
    if node is None:
        return 0
    return 1 + length(node[1])


chain = None
for index in range(5000):
    chain = (index, chain)
print(length(chain))

The other runtimes fail in different ways. Java throws StackOverflowError, which a program can catch.8 .NET terminates the process, and no catch block can stop it.29 Go stops with a fatal error when a goroutine stack passes its maximum, which is 1 GB on 64-bit systems by default.16 Rust aborts the process. sys.setrecursionlimit raises the limit of CPython, but a limit that is too high can crash the interpreter.19 -Xss raises the stack size of the JVM threads.10 Both move the failure and do not remove it. A loop keeps one frame for the whole walk.

def length(node):
    count = 0
    while node is not None:
        count += 1
        node = node[1]
    return count


chain = None
for index in range(5000):
    chain = (index, chain)
print(length(chain))
Output
5000

For a tree, keep the nodes that wait for a visit in a list on the heap, and use the list as an explicit stack.

A value type is a copy

A C# struct is copied on assignment, on a call, and on a return.25 The indexer of a List<T> returns a copy of the element. A method call on that copy changes the copy, and the list keeps the old value.

This code runs but gives a wrong answer on purpose.

using System;
using System.Collections.Generic;

var totals = new List<Total> { new Total() };
totals[0].Add(5);
Console.WriteLine(totals[0].Value);

struct Total
{
    public int Value;

    public void Add(int amount) => Value += amount;
}
Output
0

The program prints 0, not 5. Read the element into a local, change the local, and store it back. A class also fixes it, at the cost of a heap object for each element.

using System;
using System.Collections.Generic;

var totals = new List<Total> { new Total() };
var first = totals[0];
first.Add(5);
totals[0] = first;
Console.WriteLine(totals[0].Value);

struct Total
{
    public int Value;

    public void Add(int amount) => Value += amount;
}
Output
5

Boxing has the same trap. A boxed struct is a separate copy on the heap, so a change to the original does not reach it (see the C# example).26

Cost

A stack allocation. A call moves the stack pointer by the size of the frame, and the return moves it back. The JVM specification notes that the sizes of the local variable array and the operand stack are known at compile time. So the whole frame can be allocated at once at the call.8 The release costs nothing more than the return. The Rust book says that "Pushing to the stack is faster than allocating on the heap", because the allocator never has to search for a place: the place is always the top of the stack.32

A heap allocation. The program calls the allocator. The allocator searches its free blocks and updates its records, and it can ask the operating system for more memory. Later a release, a reference count, or a collector gives the block back. The C# guide calls boxing computationally expensive compared with a plain assignment, because it must allocate and build an object.26 CPython uses pymalloc for objects of 512 bytes or less, and pymalloc takes them from arenas of 1 MiB on 64-bit platforms.21 In a collected language each heap allocation also adds work for the collector, so fewer allocations mean fewer collections. Reads cost more too: "Accessing data in the heap is generally slower than accessing data on the stack because you have to follow a pointer to get there."32

Counting allocations. Go gives an exact count. testing.AllocsPerRun runs a function many times and returns the average number of heap allocations per run, which is always a whole number.17 In this run, returning a value allocates nothing. Returning a pointer to a local allocates the local. Returning a closure allocates the function value and the captured variable.

package main

import (
	"fmt"
	"testing"
)

type order struct{ id, total int }

func newOrder(id int) *order {
	o := order{id: id, total: 100}
	return &o
}

func makeOrder(id int) order {
	return order{id: id, total: 100}
}

func counter() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}

var (
	sinkPointer *order
	sinkValue   order
	sinkFunc    func() int
)

func main() {
	fmt.Println("return a value:", testing.AllocsPerRun(100, func() { sinkValue = makeOrder(1) }))
	fmt.Println("return a pointer to a local:", testing.AllocsPerRun(100, func() { sinkPointer = newOrder(1) }))
	fmt.Println("return a closure:", testing.AllocsPerRun(100, func() { sinkFunc = counter() }))
}
Output
return a value: 0
return a pointer to a local: 1
return a closure: 2

This page shows no allocation count for Java. HotSpot escape analysis can remove allocations from compiled code, so a count depends on the compiler and on when it runs.9

Stack size. The stack of each thread has a limit. HotSpot uses 1024 KB by default on Linux/x64 and 2048 KB on Linux/AArch64 and macOS/AArch64, and -Xss changes it.10 A thread that Rust spawns gets 2 MiB on all Tier-1 platforms, and Rust does not decide the stack size of the main thread.31 A goroutine starts with a few kilobytes. Its stack can grow to 1 GB on 64-bit systems and 250 MB on 32-bit systems.1316 A large local array can use up the stack at once: C# documents a StackOverflowException for a stackalloc that is too large.28

History

  • 1946. Stacks "entered the computer science literature in 1946", when Alan Turing used the words bury and unbury for the call of a subroutine and the return from it.35
  • 1955. Klaus Samelson and Friedrich L. Bauer "proposed the idea of a stack called Operationskeller", and they filed a patent in 1957.35
  • 1960. Edsger Dijkstra published "Recursive Programming". He described a stack with a stack pointer that holds the working space of each subroutine call. With it, a subroutine can be called again before its earlier calls end. He applied it to the object programs of an ALGOL 60 compiler.1
  • 1999. Choi, Gupta, Serrano, Sreedhar and Midkiff presented escape analysis for Java at OOPSLA.2 The HotSpot server compiler implements their flow-insensitive algorithm and has it on by default from Java SE 6u23.9
  • 2014. Go 1.3, released on 18 June 2014, replaced segmented goroutine stacks with contiguous stacks. A goroutine that needs more stack gets a larger single block, and the runtime copies the old stack into it.1415
  • 2022. CPython 3.11, released on 24 October 2022, stopped calling the C interpreter function for each call from Python code to Python code. It also builds frame objects only when a debugger or an introspection function asks for them. Most Python calls since then use no C stack space.2324

References

  1. Edsger W. Dijkstra, Recursive Programming, Numerische Mathematik 2, 1960, sections The Aim and The Stack (the stack pointer that points to the first free place)
  2. Jong-Deok Choi, Manish Gupta, Mauricio Serrano, Vugranam C. Sreedhar and Sam Midkiff, Escape analysis for Java, OOPSLA 1999, the paper as a whole, cited by the HotSpot documentation as the algorithm of its server compiler
  3. N3096, ISO/IEC 9899:2023 working draft (C23), 6.2.4 Storage durations of objects, paragraphs 1, 2, 5, 6 and 7; 7.24.3 Memory management functions, paragraph 1
  4. Working Draft, Programming Languages: C++, [basic.stc.auto], 6.8.6.4 Automatic storage duration, paragraph 1
  5. Working Draft, Programming Languages: C++, [basic.stc.dynamic.general], 6.8.6.5.1 Dynamic storage duration, General, paragraph 1
  6. Clang documentation, AddressSanitizer, Usage (the list of detected errors); Stack Use After Return (UAR)
  7. Clang documentation, Diagnostic flags in Clang, -Wreturn-stack-address
  8. The Java Virtual Machine Specification, Java SE 25 Edition, Chapter 2, 2.5.2 Java Virtual Machine Stacks; 2.5.3 Heap; 2.6 Frames
  9. Java SE 25 Java Virtual Machine Guide, Java HotSpot Virtual Machine Performance Enhancements, Escape Analysis
  10. Java SE 25 tool specifications, The java Command, Extra Options for Java, -Xss; Advanced JIT Compiler Options for java, -XX:+DoEscapeAnalysis
  11. The Java Language Specification, Java SE 25 Edition, Chapter 5, 5.1.7 Boxing Conversion
  12. Go FAQ, How do I know whether a variable is allocated on the heap or the stack?
  13. Go FAQ, Why goroutines instead of threads?
  14. Go 1.3 Release Notes, Changes to the implementations and tools, Stack
  15. Go release history, go1.3 (released 2014-06-18)
  16. Go standard library, package runtime/debug, func SetMaxStack
  17. Go standard library, package testing, func AllocsPerRun
  18. Go command documentation, cmd/compile, Command Line, flag -m
  19. The Python Standard Library, sys, Python 3.14, sys.getrecursionlimit and sys.setrecursionlimit
  20. The Python Standard Library, Built-in Exceptions, Python 3.14, RecursionError
  21. Python/C API Reference Manual, Memory Management, Python 3.14, Overview; The pymalloc allocator
  22. The Python Language Reference, Data model, Python 3.14, 3.1 Objects, values and types (the CPython note on id)
  23. What's New In Python 3.11, Faster CPython, Cheaper, lazy Python frames; Inlined Python function calls
  24. PEP 664: Python 3.11 Release Schedule, Release Schedule, 3.11.0 final
  25. C# language reference, Value types, the introduction (copy on assignment, argument passing and return)
  26. C# programming guide, Boxing and Unboxing, the introduction; Performance; Boxing
  27. C# language reference, ref structure types, the introduction and the list of restrictions
  28. C# language reference, stackalloc expression, the introduction; the rules on the amount of stack memory
  29. .NET API, StackOverflowException Class, Remarks
  30. The Rust Standard Library, module std::boxed, module documentation, Examples (moving a value from the stack to the heap; recursive data structures)
  31. The Rust Standard Library, module std::thread, Stack size
  32. The Rust Programming Language, What Is Ownership?, The Stack and the Heap
  33. MDN Web Docs, JavaScript execution model, The engine and the host
  34. Eric Lippert, The Stack Is An Implementation Detail, Part One, Fabulous Adventures In Coding, the whole post
  35. Stack (abstract data type), Wikipedia, History

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/8WW7BE/text.yaml