Stack
Course: Computer Architectures
Type: Concept
Definition
The stack is a memory region used in last-in, first-out (LIFO) order.
In RISC-V, sp is the ABI name for register x2.
Core idea
To reserve stack space, move the stack pointer downward:
addi sp, sp, -4To release that space later:
addi sp, sp, 4A simplified push-like pattern:
addi sp, sp, -4
sw ra, 0(sp)A simplified pop-like pattern:
lw ra, 0(sp)
addi sp, sp, 4Why different functions do not overwrite each other
Suppose:
initial sp = 1000Function A:
sp = 996
save A's value at 996Function B:
sp = 992
save B's value at 992Function C:
sp = 988
save C's value at 988Each function moves sp first, so each gets a different stack slot.
Return-address stacking
If calls happen:
main -> A -> B -> Creturns happen:
C -> B -> A -> mainThat reverse order matches LIFO behavior perfectly.
Important note
In real ABI-compliant code, stack frames are typically aligned more carefully than the simplified 4-byte examples.