Topics / RTOS & Real-Time Systems / Q23
How much stack does a task need and how do you size it?
Short answer: Estimate it from the worst-case call depth of the task's code (local variables, saved registers, function arguments, padding) plus the context-switch frame (16 words on Cortex-M, plus 18 more for FP context if the task uses the FPU, and on some ports a little more). Then measure under worst-case conditions with the high-water mark and add a safety margin (20–50%). Interrupts use the main stack on Cortex-M, so they do not need to be included in task stacks.
Step by step
- Static analysis: compile with
-fstack-usageto get each function's frame size, and combine with the call graph (-fcallgraph-info, puncover, or commercial tools) to get the worst path. Recursion and function pointers need manual bounds. - Add the context frame and any library calls that are stack-hungry (
printf/snprintfwith floating point can use 500 bytes to 1 KB or more). - Measure: run stress tests that exercise every path, then check
uxTaskGetStackHighWaterMark(handle)(minimum free stack ever, in words). FreeRTOS fills stacks with0xA5to measure this. - Margin: keep 25% or more free in the worst measured case, since tests rarely hit the true worst case.
Protection during development and in the field
configCHECK_FOR_STACK_OVERFLOW = 2(check pattern at each switch) andvApplicationStackOverflowHook().- MPU guard regions (FreeRTOS-MPU, Zephyr
CONFIG_HW_STACK_PROTECTION) or Armv8-M PSPLIM for immediate faults. - Log the minimum free stack per task in diagnostics.
Reducing stack needs
- Move large buffers out of local variables into static memory or pools.
- Avoid
printf-family functions in small tasks; use a logging task. - Avoid deep call chains and recursion; avoid variable-length arrays and
alloca. - Watch for large structs passed by value.
Typical values: simple tasks 128–256 words (512 B–1 KB) on Cortex-M; tasks using TLS, filesystems or networking several KB.