Stack Size Estimator — worst-case depth

Estimate worst-case stack depth from call nesting, locals and interrupt frames.

Example: A worst case of about 832 bytes suggests allocating 1248 bytes of stack at a 1.5× margin.

Check it against real silicon

Chiprun runs your firmware on an emulated microcontroller and hands back the UART output, so you can confirm these numbers rather than trusting them.

Chiprun docs

Formula

stack = deepest call chain + interrupt frames + margin

Worked example

A worst case of about 832 bytes suggests allocating 1248 bytes of stack at a 1.5× margin.

  1. call tree = depth × frame + largest buffer

    8 × 48 + 256

    640 bytes

  2. interrupts = nesting × frame

    2 × 96

    192 bytes

    Interrupts stack on top of the deepest point of the call tree, not beside it.

  3. recommended = (call tree + interrupts) × margin

    832 × 1.5

    1248 bytes

Frequently asked questions

How much stack does an embedded application need?

It depends entirely on the deepest call chain and the largest local buffers in it. A simple bare-metal loop might need 512 bytes; anything using printf, a filesystem or a network stack can need several kilobytes. Estimate first, then measure.

Why do interrupt frames matter so much?

Because an interrupt can arrive at the deepest point of your call tree, and its frame stacks on top. Nested interrupts add more. Sizing for the call tree alone works on the bench and overflows in the field, when an interrupt happens to land at the wrong moment.

How do I measure actual stack usage?

Fill the stack region with a known pattern at boot, run the firmware through its heaviest workload, then look for the highest address still holding the pattern. That high-water mark is your real peak. GCC's -fstack-usage plus a call-graph analyser gives a static bound too.

What happens when the stack overflows?

Usually nothing obvious at first. It writes past its allocated region into whatever is next in RAM — commonly globals — and the corruption surfaces later somewhere unrelated. That is why an MPU guard region or a stack canary is worth the setup cost.

Related tools