Chapter 15

Gravity (Stacks)

We enter Phase IV. Programming books usually introduce data structures as "Abstract Data Types" or "Containers".

This is a lie.

A Data Structure is not a container. It is a negotiation with the machine. You promise to restrict your behavior, and in exchange, the machine grants you speed.

The Stack is the strictest negotiation of all.

The Contract: Gravity

The Stack enforces a brutal rule: You can only touch the top. You cannot move sideways. You cannot jump to the bottom. Gravity pulls everything down.

Why would anyone accept such a limited tool? Because in exchange, the machine gives you everything.

Physics Lens: Cache ↑↑↑ (Hot Top) | TLB ↑↑↑ (Same Page) | Prefetch ↑↑ (Linear) | Coherence ↑↑ (Private)
Experiment: PUSH and POP. Notice that the "Hot" data (Top) is always close to where you were before. You never jump far.

The Four Lenses

Let's audit the Stack against our hardware realities.

The Stack is the closest thing to a survivor the memory hierarchy allows. It is the only structure that the machine truly loves.

What Gravity Forbids

The Stack is fast because it forbids freedom.

These are not design flaws. They are the price of speed.

The stack is not just for data. It is how the CPU remembers where it was. Without the stack, there is no call, no return, no recursion, no structured execution.

Hypotheses
Why do recursive functions crash the stack?

Because the contract of "Gravity" assumes you will eventually stop falling. The Stack has finite physical space (often 1MB-8MB). Infinite recursion breaks the negotiated limit.

Why are "Stack Allocations" faster than "Heap Allocations"?

Malloc (Heap) has to search for free space (O(N) or worse) and update metadata. Alloca (Stack) just subtracts a number from a register (SP). One instruction vs thousands.

Why not put everything on the stack?

Because the stack assumes strict lifetime ordering. If data must outlive its creator, be shared, or be accessed out of order, the stack contract breaks. The machine gives speed only if you give up freedom.

What programmers usually get wrong here

They think the Stack is small because RAM is expensive. No. The Stack is small because it *must* stay hot in L1 cache to be fast. If the stack were 100GB, you would lose the locality benefit.

This works — until we need to wait. The Stack implies "Last In, First Out". But the real world often works "First In, First Out". We need a Line.