Home / Learn Chip Programming / The Stack, Function Calls and Memory Layout
The Stack, Function Calls and Memory Layout
The stack stores return addresses and local variables. Understanding it explains crashes, recursion limits and security bugs.
Theory in plain words
What it is
The stack is a region of RAM used like a pile of plates. The last thing pushed is the first popped (LIFO). The stack pointer (SP) always points at the top.
Why we use it
Functions need somewhere to keep their return address, parameters and local variables. The stack does this automatically and supports nested and recursive calls.
How it works
CALL pushes the return address and jumps. The function pushes registers it must preserve and reserves space for locals. RET pops the return address into the PC. On most chips the stack grows downward in memory.
Where it is used
- Every function call in C
- Interrupt handling (registers are saved on the stack)
- RTOS: each task has its own stack
- Security: stack buffer overflow
Sections of a compiled program
| Section | Lives in | Contains |
|---|---|---|
| .text | Flash | your machine code |
| .rodata | Flash | constants and strings |
| .data | RAM (copied from Flash at boot) | initialised globals |
| .bss | RAM (cleared at boot) | uninitialised globals |
| stack | RAM | locals, return addresses |
| heap | RAM | malloc blocks |
Try pushing past the limit: the real chip does not show an alert, it silently overwrites other variables or crashes with a hard fault.
char buf[4096]; inside a function). Make them static or global. Never use deep recursion. Check the stack usage with the linker map or a stack watermark.Calling convention (ARM)
The first four arguments go in R0 to R3, the return value comes back in R0, and the function must preserve R4 to R11. The calling convention is a rule everyone agrees on so that code from different compilers can call each other.
Quick quiz
1. Which data lives on the stack?
Calls and locals use the stack.
2. Why avoid big local arrays on a small MCU?
Stack overflow corrupts memory silently.
Common questions
Which data lives on the stack?
Return addresses and local variables. Calls and locals use the stack.
Why avoid big local arrays on a small MCU?
The stack is only a few KB and can overflow. Stack overflow corrupts memory silently.