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.

In shortThe stack grows with every function call. PUSH saves a value, POP restores it. Local variables live there. Too deep and it overflows into other memory.

Theory in plain words

RAM layout of a microcontroller programStack (grows down from the top of RAM)Free space between stack and heapHeap: malloc / new (grows up).bss: global variables initialised to 0.data: global variables with a start value (copied from Flash)
RAM layout of a microcontroller program

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

SectionLives inContains
.textFlashyour machine code
.rodataFlashconstants and strings
.dataRAM (copied from Flash at boot)initialised globals
.bssRAM (cleared at boot)uninitialised globals
stackRAMlocals, return addresses
heapRAMmalloc blocks
Watch the stack grow and shrinkTry it Yourself

Try pushing past the limit: the real chip does not show an alert, it silently overwrites other variables or crashes with a hard fault.

Careful:Never put big arrays on the stack of a small microcontroller (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?

2. Why avoid big local arrays on a small MCU?

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.