L1 · HardwareComputer Science 101 · part 2 of 2

Memory: The Stack, the Heap, and Pointers

Where your variables actually live, why the heap costs more than the stack, and what a pointer really is.

Takumi Yamada
· 5 min read · 2 references
memorystackheappointersgo

It's easy to picture memory as one long row of identical .

In practice there are several kinds of storage. The fast kinds are small, and the big kinds are slow. The memory your program can use is also split into areas that are used in different ways. Knowing this layout explains , stack overflows, and how Go decides where to put your variables.

The memory hierarchy

The (Central Processing Unit) needs data quickly, but large storage is slower than small storage. So computers use several layers of storage. Each layer is roughly ten times faster, and much smaller, than the layer below it.

LevelTypical sizeTypical
a few hundred bytesunder 1 cycle, about 0.3 ns
L1 32 to 64 KBabout 1 ns
L2 cache256 KB to 1 MBabout 4 ns
L3 cache8 to 32 MBabout 15 ns
8 to 128 GBabout 100 ns
0.5 to 4 TBabout 100,000 ns

Registers are the few storage slots inside the CPU. A cache is a small, fast memory on the processor chip that keeps copies of recently used data. RAM (Random Access Memory) is the computer's main memory, and an SSD (Solid-State Drive) is where files are stored. The last step is the biggest: an SSD is roughly a thousand times slower than RAM.

ONE READIF A CYCLE TOOK 1 SECONDREGISTERS0.3 ns1 secondL1 CACHE1 ns3 secondsL2 CACHE4 ns13 secondsL3 CACHE15 ns50 secondsRAM100 ns5 and a half minutesSSD100,000 nsalmost 4 days
The table above as a ladder. The last column stretches time so that one CPU cycle lasts one second.

Fast software keeps the data the CPU needs in the top few rows. The caches help automatically. When you read one byte, the cache loads the 64 bytes around it, which is called a cache line. So when your next read is the byte right after, it's already in the cache. That's why reading memory in order is much faster than jumping to random places by following pointers.

IN ORDERa slice, an arrayone cache line, loaded by the first readBY POINTERa list, a treeeach hop lands somewhere else, so each one can miss the cache
The same memory read in order and by following pointers.

Inside your process: stack versus heap

A running program is called a process. When it starts, the gives it its own range of . Two areas in that range matter most.

The stack grows and shrinks automatically as functions are called and return. It's fast, it's used in strict order, and it has a fixed limit, usually between 1 and 8 MB.

The heap is for data that has to stay alive after the function that created it returns, or whose size isn't known until the program runs. It's flexible. In C you free heap memory yourself. In Go a garbage collector finds memory that is no longer used and frees it for you.

high addresseslow addressesSTACKfreeHEAPGLOBALSCODEone frame per call,grows downwardallocated on demand,grows upward
One process's address space. The stack and the heap grow toward each other.

Stack frames

Every function call adds a stack frame to the . A frame is a block of memory that holds the call's local variables, its arguments, and the return address, which is where to continue when the function finishes.

When the function returns, its frame is removed at once. The CPU only moves a register called the stack pointer back up. There is no searching for free space and no record keeping. Making room on the stack is one subtraction, and freeing it is one addition.

CALLER'S FRAMEadd's localssaved registersreturn addressfreestack pointer beforestack pointer afterthe frame for add():pushed by the call,popped by the return
The frame for one call. Pushing it and popping it are both just a change to the stack pointer.

That's why stack allocation costs almost nothing. It's also why a function that calls itself forever causes a stack overflow. Frames keep being added until the stack's limit is reached.

What a pointer actually is

A pointer is a variable whose value is a memory address. An address is a number that names one location in memory. On a 64-bit machine, a pointer is eight bytes holding something like "the data is at byte 0x7ffd".

x := 42
p := &x      // p holds the address of x
fmt.Println(*p) // dereference: go to that address, read → 42
*p = 7          // go to that address, write
fmt.Println(x)  // → 7

The ampersand, &, means "give me the address of this". The asterisk, *, means "go to that address and use what is there". These are the only two things you do with pointers.

p := &xp0x7ffdan addressx, at 0x7ffd42p holds where x is,not what x is*p = 7p0x7ffdan addressx, at 0x7ffd7go to that addressand write there
The code above, before and after the write through p.

Everything built from pointers, such as linked lists, trees, and methods with pointer receivers, comes down to storing addresses and following them.

Why heap allocation costs more

On the stack, making room means moving one register. On the , the allocator, the code that hands out heap memory, has to find a free block that is big enough and mark it as used. In Go, the garbage collector later has to check whether anything still points at that block before it can free it.

STACKone stepusedusednewfreestack pointermoves past the new block, and that is allHEAPa searchusedusedusednewusedtoo smallfitsThe allocator looks for a free block that is big enough.Later the garbage collector has to check whether it is still used.
The same allocation on the stack and on the heap.

The stack never does any of that work. Objects on the heap also tend to be spread out in memory. Following pointers between them often misses the cache, and each miss costs about 100 ns to reach RAM.

Stack allocation costs almost nothing and cleans up after itself. Heap allocation costs time twice, once to find space and again to free it later, and it often makes reads slower by missing the cache. Use the stack when you can.

Escape analysis: who decides?

In Go you never ask for heap memory directly. The decides between the stack and the heap, using a check called escape analysis.

If the compiler can prove that a value isn't used after its function returns, the value goes on the stack. If a reference to it escapes, the value has to go on the heap. A reference escapes when it's returned, stored in a global variable, or captured by a function that lives on after the call.

func stackAlloc() int {
    v := 10      // never escapes → stays on the stack
    return v     // the value is copied out
}

func heapAlloc() *int {
    v := 10      // its address escapes via the return
    return &v    // must live on the heap
}

You can ask the compiler to show its decisions.

$ go build -gcflags='-m' main.go
./main.go: v doesn't escape
./main.go: moved to heap: v

In stackAlloc, the value stays on the stack and is freed for free when the function returns. In heapAlloc, we return the value's address, so the value has to stay alive after the frame is gone. Go puts it on the heap, and from then on the decides when to free it.

func stackAlloc() intCALLERx = 10POPPEDv = 10the value is copied outv dies with its frame. Nothing to clean up.func heapAlloc() *intCALLERpPOPPEDHEAPv = 10v outlives the call, so the garbage collector owns it.
What is left once each function has returned.

The two functions look almost the same, but their costs are very different, and one compiler flag tells you which is which.

The Bottom Line

I write Go tools on Arch, and most questions that start with "why is this allocating" are answered by this section.

If a busy loop returns the address of something on every pass, each pass gives the garbage collector more work. If you pass values instead, reuse buffers, or keep values from escaping, the memory moves onto the stack, where it costs almost nothing.

Registers, then cache, then RAM, then disk. The stack is cheap, and the heap costs more. With those two facts, you can reason about any decision about memory or pointers.

Check yourself

3 questions · nothing is saved
  1. 1.Your program reads one byte that isn't in the cache. What does the cache load?
  2. 2.Why does putting something on the stack cost almost nothing?
  3. 3.In Go, which of these makes a value go on the heap?

References & Primary Sources

Official specifications, standards, and documentation cited in this post.

  1. [1]

    Defines the x86-64 execution stack frame conventions, register allocation, and call stack layout.

    SPECgitlab.com
  2. [2]

    Standard specification for dynamic memory allocation, alignment, and process heap management.

    STANDARDpubs.opengroup.org

Who wrote this

Author profile and background

Takumi Yamada

Takumi Yamada

· Backend Engineer

Backend engineer building services, databases, Linux tooling, and NEGEN SYSTEMS. Writing about low-level mechanics, distributed systems, and real-world security.

End of post
NEGEN SYSTEMS
Receipt · post 2 of 31
Written
Oct 22, 2025
Length
1,178 words · 5 min
Built
…
Served by
…
Delivered
…
Over the wire
…
Go's share
…
Next up the stack · L1 Hardware

USB Sticks, Disks, and the Mysterious 4GB Wall

Why a 64GB USB stick refuses a 5GB file, what a file system actually is, and how FAT32, exFAT and NTFS really differ inside.

8 min read
From other series