Home / Learn Embedded C / The Stack in Embedded Systems

The Stack in Embedded Systems

How function calls, local variables and return addresses all live on one small region of RAM.

Quick summaryHow function calls, local variables and return addresses all live on one small region of RAM.

How to think about this

What happens on the stack during a function callmain() callsprocess_reading()A new stack frame ispushed (locals +…process_reading()runs, using its own…process_reading()returnsIts stack frame ispopped; back in…
What happens on the stack during a function call

Definition

The stack is a last-in-first-out region of RAM that holds each active function call's local variables and its return address, growing with every call and shrinking on every return.

Why you need this

A microcontroller might budget only a few hundred bytes to a couple of kilobytes for the entire stack — every local variable, every level of function call (and especially recursion) eats into that fixed budget.

How it works

Calling a function pushes a new "stack frame" (its locals + return address); returning pops that frame off. Deep call chains, large local arrays, or recursion can all exhaust the stack.

Where you'll see this

  • Stack-budget planning
  • Debugging crashes
  • Recursion limits

Try it

Watching the call stack grow and shrink through printfC: edit and run

Each indentation level corresponds to one more stack frame pushed on top of the previous one.

Careful:A large local array (like "char buffer[2048];" inside a function) can overflow the stack on a small chip instantly, even without any recursion at all.

Try it: watching recursion push frame after frame

Tracking recursion depth as frames pile upC: edit and run

Each recursive call pushes one more frame before any start popping — deep or unbounded recursion is exactly how a stack runs out of room.

Test what you just read

1. What happens to a function's local variables when it returns?