Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 40 ยท The Stack and Functions

The Stack: push, pop and rsp

Learn how the stack works in x86-64 assembly: push and pop move rsp, the stack grows downward, 16-byte alignment, the red zone, and scratch space. Runnable toy CPU.

Registers are fast but there are only a handful of them. Sooner or later a program needs somewhere to park a value for a while, to remember where to return to after a function call, or to hold the local variables of a function. The answer on practically every CPU is the stack: a region of memory managed in last-in, first-out order, with a special register, the stack pointer (rsp on x86-64, sp on ARM64), that always marks its current end.

This lesson explains exactly what push and pop do, in which direction the stack grows, the alignment rule you must obey, the red zone, and how to use the stack as scratch space. The stack is the base for CALL and RET in the next lesson. If memory addresses are new to you, review Memory, Addresses and Endianness first. All runnable examples use the toy CPU, where rsp starts at 0x1000 (4096) and every stack slot is 8 bytes wide, as on x86-64.

What push and pop really do

On x86-64, push and pop are shorthand for two steps each:

NASM
push rax        ; rsp = rsp - 8      then      store rax at [rsp]
pop  rbx        ; load [rsp] into rbx    then    rsp = rsp + 8

So push rax is the same as sub rsp, 8 followed by mov [rsp], rax, only shorter. And pop rbx is mov rbx, [rsp] followed by add rsp, 8. The important points:

  • rsp always points at the most recently pushed value (the top of the stack).
  • Each push moves rsp by the size of the item, 8 bytes for a 64-bit register.
  • The stack grows downward, toward smaller addresses. This is true for x86-64, ARM64 and most other mainstream architectures.
  • pop does not erase anything. It only reads the value and moves rsp back. The old value stays in memory until something overwrites it, which is why reading a stale stack slot can show "ghost" values.
flowchart TB
  A["0x1000: start (rsp before any push)"] --> B["0xff8: 11 (pushed first)"]
  B --> C["0xff0: 22"]
  C --> D["0xfe8: 33 (rsp points here after 3 pushes)"]

Higher addresses are at the top of the picture: each push moves the stack pointer to a lower address.

Why downward? Historically the code and data sat at low addresses, and the stack started at the top of memory growing down while the heap grew up, so the two could share free space between them. The convention stuck.

Watch rsp move

Push three values, then pop them into three other registers. The trace prints rsp before each instruction (as a decimal number: 4096 is 0x1000), and the program ends by printing the memory the stack used.

JS Three pushes, three pops

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can read it straight from the trace: rsp goes 4096, 4088, 4080, 4072 as the three pushes happen, and returns to 4096 after the pops. The values come back in reverse order: 33 first, 11 last. The memory dump at the bottom shows that all three values are still there at 0xff8, 0xff0 and 0xfe8 even though the stack is "empty" again.

The stack as scratch space

Because pop undoes push, you can use the stack to borrow a register for a moment. A function that must use rbx but promised to leave it unchanged saves it first and restores it afterwards:

NASM
push rbx          ; save the caller's rbx
; ... use rbx for something else ...
pop  rbx          ; restore it

Pushes and pops must be balanced: whatever you push inside a block you must pop before leaving it, in reverse order. An unbalanced stack is among the most common causes of crashes in hand-written assembly, because a later ret will read the wrong value as its return address.

The same trick swaps two registers, since the order reverses, and reverses any list of values.

JS Swap with the stack, then reverse five numbers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first two lines show the swap (2 then 1). The next five print 50, 40, 30, 20, 10: the push order 10 to 50 comes back reversed. Real programs also use the stack to hold values across a call, as you will do in CALL and RET.

Alignment: the 16-byte rule

Both pushes and pops move rsp in 8-byte steps, but the common calling conventions demand more: on System V x86-64 (Linux and macOS) and on Windows x64, rsp must be a multiple of 16 at the moment of a call instruction. The call itself then pushes an 8-byte return address, so inside the called function, right at its first instruction, rsp is 8 modulo 16. Many compilers restore the 16-byte alignment by starting a function with push rbp (another 8 bytes) or sub rsp, 8.

Why does the CPU care? Some instructions that move 16 bytes at once (movaps, used for SSE vectors) fault when the address is not a multiple of 16, and compilers happily use them for stack variables. A misaligned stack typically shows up as a crash deep inside a library call such as printf, far away from the actual mistake. ARM64 is stricter: the hardware requires sp to be 16-byte aligned whenever it is used to access memory.

The JavaScript below is not a CPU; it is a small calculator for the bookkeeping. It tells you whether rsp would be aligned at a call, given the number of 8-byte pushes in a function and an optional extra sub rsp, N.

JS Is the stack aligned at the next call?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The output alternates: zero pushes is misaligned (only the return address is on the stack), one push fixes it, two breaks it again, and so on. The rule of thumb is to count in 8-byte units: an odd number of pushes (the return address is the first unit) keeps you aligned.

The red zone

On System V x86-64, the 128 bytes below rsp are reserved for the running function: the red zone. A leaf function (one that calls nothing) may store local variables there without moving rsp, saving a sub and an add. Signal and interrupt handlers are set up to skip over it, so the data is safe.

NASM
square_via_stack:
        mov   DWORD PTR [rsp-4], edi   ; a local variable below rsp, no sub rsp needed
        mov   eax, DWORD PTR [rsp-4]
        imul  eax, eax
        ret

That is an illustrative leaf function; real compilers would simply keep the value in a register. Three limits matter: a function that makes a call must not rely on the red zone (the call would overwrite it with the return address); Windows x64 has no red zone; and kernel code is built without it (-mno-red-zone) because interrupts can arrive at any time and use the current stack.

The toy CPU has neither alignment checks nor a red zone. Its only protection is a stack floor: if rsp drops below 0xe00 the toy stops with "stack overflow", just as a real process dies with a segmentation fault when the stack runs out of space.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does push rax do on x86-64?

    The stack grows downward, so push first decrements rsp by 8 and then writes the value at [rsp]. Pop reads the value and then adds 8.
  2. 2. After pop rbx, what happens to the value that was on the stack?

    pop only reads the slot and moves rsp up. The bytes remain, which is why stale values may be visible and why secrets on the stack should be cleared explicitly.
  3. 3. At the first instruction of a System V x86-64 function, what is rsp modulo 16?

    The caller must have rsp a multiple of 16 before call. call pushes 8 bytes, so the callee starts at 8 modulo 16 and often fixes it with push rbp or sub rsp, 8.
  4. 4. Which statement about the red zone is correct?

    System V x86-64 guarantees that 128 bytes below rsp stay intact for the running function. Windows x64 and kernel code do not have it, and a function that calls other functions cannot use it.

Summary

  • The stack is a last-in, first-out region of memory; rsp points at its top.
  • push decrements rsp by 8 and stores; pop loads and increments rsp by 8. The stack grows toward lower addresses.
  • pop does not erase memory; pushes and pops must be balanced or later ret instructions will misbehave.
  • The stack is natural scratch space: save and restore registers, swap values, reverse lists.
  • On System V and Windows x64, rsp must be 16-byte aligned at a call; inside the callee it is 8 modulo 16 at entry. ARM64 requires a 16-byte aligned sp for memory access.
  • The 128-byte red zone below rsp is a System V x86-64 feature for leaf functions; Windows and kernel code do not have it.

Next: see how call and ret use the stack to find their way back in CALL and RET.