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, -4

To release that space later:

addi sp, sp, 4

A simplified push-like pattern:

addi sp, sp, -4
sw   ra, 0(sp)

A simplified pop-like pattern:

lw   ra, 0(sp)
addi sp, sp, 4

Why different functions do not overwrite each other

Suppose:

initial sp = 1000

Function A:

sp = 996
save A's value at 996

Function B:

sp = 992
save B's value at 992

Function C:

sp = 988
save C's value at 988

Each function moves sp first, so each gets a different stack slot.

Return-address stacking

If calls happen:

main -> A -> B -> C

returns happen:

C -> B -> A -> main

That 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.