Where Values Live
In the last chapter, we saw that bits are just raw material. But where do we put them?
If you write int a = 10; in C, where does 10 strictly exist?
It lives on The Stack.
The Dumbest Allocator
The Stack is the backbone of all function calls, yet it is incredibly primitive. It is just a pointer called SP (Stack Pointer).
Allocation (Push): Decrement SP. Write data.
Deallocation (Pop): Increment SP.
That's it. No searching for free space. No garbage collection. Just moving a pointer. This speed is why 90% of your program's variables live here.
The Ghost
When you "return" from a function, your variables are not deleted. The Stack Pointer simply moves back up. The data—your passwords, your keys, your embarrassing logs—remains in memory until the next function call overwrites it.
This leads to the class of bugs called Buffer Overflows and Uninitialized Memory usage. If you read from an uninitialized variable, you are reading the ghost of the previous function's state.
What a Stack Frame Really Contains
A stack frame is not just your variables. It also stores:
- The return address (Where to go back to)
- Saved registers (Restoring the previous state)
- Alignment padding (Wasted air)
Overwriting any of these changes control flow. This is not a bug. It is how the machine works.
Why does the Stack grow downwards?
Pure history. In early architectures, the Heap started at the bottom (low addresses) and grew up, while the Stack started at the top (high addresses) and grew down. This maximized the shared free space between them. If they met in the middle, you ran out of RAM (Stack Overflow).
What is a Stack Overflow?
It happens when you PUSH too much—usually due to infinite recursion. The Stack Pointer moves lower and lower until it hits the end of the reserved memory region (or collides with the Heap/Code). The CPU triggers a fault, and your program crashes.
Why can't I return a pointer to a stack variable?
Because as soon as the function returns, the Stack Pointer moves. That memory is now marked as "free". The next interrupt or function call will ruthlessly overwrite it. Your pointer now points to garbage (or worse, a new, valid variable that you will corrupt).
What programmers usually get wrong here
Assuming local variables are "private". They are just data sitting in RAM. If you pass the address of a local variable to another thread or function, they can modify it even after you return. This leads to Use-After-Return bugs.
Modern systems add guard pages and red zones to detect stack corruption — but this is a patch, not a fix.
This works — until we scale it. The Stack is fast, but it is tiny. If we need more space, we must leave this safe haven.