← Workshop home / Exercise 06
EXERCISE 06

Memory Allocator — The Superstitious Allocator

Make the allocator panic on unlucky allocation sizes to expose the internals.

Exercise 6: Memory Allocator — The Superstitious Allocator

Want to learn more? Read The Memory Allocator for a high-level overview of Go’s allocator design, and browse go/src/runtime/malloc.go for the full implementation.

In this exercise, you’ll explore Go’s memory allocator by adding a deliberately absurd rule: refusing to allocate 31337 bytes because it’s unlucky. This forces you to find the central allocation entry point and understand how ALL heap allocations flow through a single function.

Learning Objectives

By the end of this exercise, you will:

  • Understand Go’s allocator hierarchy (mcache → mcentral → mheap)
  • Know how size classes work and why they exist
  • Identify mallocgc as the single entry point for all heap allocations
  • Modify the allocator and observe the effects at runtime
  • Read a panic stack trace to pinpoint the source of an allocation

Introduction: Go’s Memory Allocator

Go’s memory allocator is a heavily optimized variant of tcmalloc (Thread-Caching Malloc). It has three tiers:

The Three-Tier Hierarchy

mcache (per-P cache) Each logical processor (P) has its own mcache. Allocations from the mcache require no locking — they are fast because they never contend with other goroutines. The mcache holds a list of partially-filled memory spans for each size class.

mcentral (shared pool per size class) When an mcache runs out of a particular size class, it fetches a new span from the corresponding mcentral. This requires a lock, but only on the specific size class — different size classes don’t block each other.

mheap (the OS-level heap) When mcentral needs more memory, it requests spans from mheap, which in turn requests pages from the OS using mmap (on Linux) or similar. This is the slowest path and is taken rarely.

Size Classes

Rather than allocating exactly as many bytes as requested, Go rounds small allocations — anything up to 32768 bytes — up to one of 68 predefined size classes. For example, a 31337-byte request would be rounded up to the next size class (32768 bytes). This amortizes fragmentation and makes the free list management much simpler.

Request: 31337 bytes →  rounded up to  →  32768 bytes (size class)
Request: 33 bytes    →  rounded up to  →  48 bytes (size class)
Request: 100 bytes   →  rounded up to  →  112 bytes (size class)

There is no size class beyond 32768 bytes. That’s the largest of the 68 classes (MaxSmallSize in go/src/internal/runtime/gc/sizeclasses.go). Anything bigger is a large object, allocated directly by mheap and rounded up only to a multiple of the page size (8192 bytes) — not to any entry in the size-class table.

mallocgc: The Single Entry Point

ALL heap allocations in Go go through one function: mallocgc in runtime/malloc.go. Whether you call new(MyStruct), make([]int, 100), or take the address of a local variable that escapes — it all ends up at mallocgc.

func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer
  • size — The number of bytes to allocate
  • typ — The type descriptor (used by the GC to find pointers inside the object)
  • needzero — Whether the memory should be zeroed (true for most allocations)

Step 1: Find mallocgc

grep -n "^func mallocgc" go/src/runtime/malloc.go

You should see the function definition. Open go/src/runtime/malloc.go and read the first 30 lines of mallocgc. Notice:

  1. The zero-size check at the top — new(struct{}) returns a special zerobase pointer, no allocation needed
  2. The size-class lookup — the size is rounded up and the appropriate mcache span is chosen
  3. The GC assist logic — if the GC is running and the goroutine has debt, it helps the GC before allocating

Step 2: Understand Size Classes

Take a look at the size class table:

grep -n "SizeClassToSize" go/src/internal/runtime/gc/sizeclasses.go | head -10

You’ll see arrays mapping size class indices to byte sizes. The first few entries:

var SizeClassToSize = [NumSizeClasses]uint16{0, 8, 16, 24, 32, 48, 64, 80, 96, 112, ...}

Notice that 31337 bytes would fall between size class 28672 and 32768, so it would be rounded up to 32768 — the largest size class there is. But mallocgc is called with the original size 31337 before the rounding happens — which means we can intercept it.

Step 3: Add the Superstition

Open go/src/runtime/malloc.go and find the mallocgc function. Right after the zero-size check (the first if size == 0 block), add:

if size == 31337 {
    panic("superstitious allocator: refusing to allocate 31337 bytes — that's unlucky!")
}

The placement matters. We want to add this AFTER the zero-size shortcut but BEFORE any other logic:

func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer {
    if doubleCheckMalloc {
        if gcphase == _GCmarktermination {
            throw("mallocgc called with gcphase == _GCmarktermination")
        }
    }

    if size == 0 {
        return unsafe.Pointer(&zerobase)
    }

    // Our superstition goes here:
    if size == 31337 {
        panic("superstitious allocator: refusing to allocate 31337 bytes — that's unlucky!")
    }

    // ... rest of mallocgc

Step 4: Rebuild

cd go/src && ./make.bash

Since we’re modifying the runtime, the entire standard library needs to be recompiled. make.bash handles this automatically.

Step 5: Test With a 31337-Byte Struct

Create unlucky.go:

package main

type Unlucky struct {
    a int8        // 1 byte
    b [31336]byte // 31336 bytes
    // total: 31337 bytes
}

var sink *Unlucky // forces u to genuinely escape to the heap

func main() {
    u := new(Unlucky) // heap allocation of 31337 bytes
    sink = u
    println("made it!")
}

Run it with your modified Go:

../go/bin/go run unlucky.go

Expected output:

panic: superstitious allocator: refusing to allocate 31337 bytes — that's unlucky!

goroutine 1 [running]:
main.main()
        /tmp/unlucky.go:12 +0x1a
exit status 2

The program panics! The new(Unlucky) call, combined with the sink assignment forcing a real escape, triggered a heap allocation of 31337 bytes, which hit our check.

Step 6: Read the Stack Trace

The stack trace confirms the allocation chain:

new(Unlucky) in main.main()
  → runtime.newobject()  — the Go runtime function backing new()
    → runtime.mallocgc() — our modification panics here

By default, Go’s panic handler hides the runtime-internal frames around a panic so ordinary users aren’t shown implementation detail. Set GOTRACEBACK=system to reveal them:

GOTRACEBACK=system ../go/bin/go run unlucky.go

Which shows the full chain (trimmed here to the relevant frames — you’ll also see a few background GC/scavenger goroutines in the real output):

panic: superstitious allocator: refusing to allocate 31337 bytes — that's unlucky!

goroutine 1 [running]:
panic(...)
        go/src/runtime/panic.go:XXX
runtime.mallocgc(...)
        go/src/runtime/malloc.go:XXX
runtime.newobject(...)
        go/src/runtime/malloc.go:XXX
main.main()
        /tmp/unlucky.go:12 +0x...
exit status 2

Try making the struct stack-allocated by making it a local variable without taking its address:

func main() {
    var u Unlucky  // stack allocation — does NOT go through mallocgc
    _ = u
    println("made it!")
}

This should print made it! — u never escapes (nothing ever takes its address out of main), so mallocgc is never called.

Step 7: Extension — Explore Other Unlucky Sizes

Try blocking other sizes and see what breaks. Edit your check:

if size == 24 {
    panic("superstitious allocator: refusing to allocate 24 bytes!")
}

Rebuild and try running a simple program. You’ll find that some standard library data structure happens to be exactly 24 bytes on your platform. The panic stack trace will tell you exactly which one. 24 is a common size for slice headers (reflect.SliceHeader is pointer + int + int = 24 bytes on 64-bit) — blocking it causes spectacular failures in nearly every program.

This demonstrates something important: because ALL allocations go through mallocgc, a single check here affects the entire program including the standard library. This is both a powerful observation point and a reminder of why correctness in the allocator is critical.

Cleanup

Revert the change:

git checkout go/src/runtime/malloc.go
cd go/src && ./make.bash

Summary

Key file:    go/src/runtime/malloc.go  — mallocgc function
Signature:   func mallocgc(size uintptr, typ *_type, needzero bool) unsafe.Pointer

Hierarchy:   new(T) / make(...) / escaping variables
                 ↓
             runtime.newobject / runtime.makeslice / ...
                 ↓
             runtime.mallocgc   ← our modification lives here
                 ↓
             mcache → mcentral → mheap → OS

Size classes: 68 buckets (in go/src/internal/runtime/gc/sizeclasses.go)
             allocations rounded up to nearest class
             66613 bytes → rounded to 73728 bytes (but mallocgc sees 66613 first)

The allocator is the foundation everything rests on. Understanding it — and knowing that a single function handles all heap allocations — is essential for reasoning about performance, GC pressure, and memory safety in Go.


Return to the main workshop

← Previous
SSA & Compiler Backend — Power-of-Two Detector
Next →
Goroutine Stack — Big-Boned Goroutines