Lesson 11 of 15

The Stack: Push & Pop

The Stack

The stack is a region of memory that grows downward (from high addresses to low). The rsp register always points to the top of the stack.

Push and Pop

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

LIFO Order

The stack is Last-In, First-Out. Values come back in reverse order:

push 1         ; push first
push 2         ; push second
pop rcx        ; rcx = 2 (last pushed, first popped)
pop rdx        ; rdx = 1

Saving and Restoring Registers

A common use is saving registers you need to preserve:

push rbx       ; save rbx
; ... use rbx freely ...
pop rbx        ; restore rbx

Using the Stack for Temporary Storage

You can write directly to the stack-allocated area:

sub rsp, 8       ; allocate 8 bytes
mov BYTE [rsp], 72   ; store 'H' at [rsp]
; ... use the data ...
add rsp, 8       ; free the space

Your Task

Demonstrate that push/pop follows LIFO order:

  1. Push 3, then push 1, then push 2 onto the stack
  2. Pop all three values and print each as a digit followed by a newline
  3. The output should show them in reverse push order: "2\n1\n3\n"
x86_64 runtime loading...
Loading...
Click "Run" to execute your code.