The short answer
There’s no formula that gives you the right stack size up front. The reliable approach is:
- Start generous. Give each task more stack than you think it needs.
- Measure. Run the system through its worst-case paths and read each task’s high-water mark, the least free stack it ever had.
- Cross-check. Use compiler stack-usage reports to estimate the deepest call chain, especially for paths that are hard to trigger in testing.
- Add margin. Set the final size to the measured or calculated worst case plus a safety margin.
- Keep detection on. Leave overflow checks enabled in development, and preferably keep some form of detection in production.
The rest of this article explains each step, the units trap that catches many people, and the run-time tools in FreeRTOS, Zephyr, and ThreadX.
What uses a task’s stack
Every task in an RTOS has its own stack. It holds:
- Local variables of every function currently active in that task, including arrays and structs declared inside functions.
- Call frames. Return addresses, saved registers, and function arguments that don’t fit in registers. Deep call chains add up.
- The saved context. When the task is switched out, its CPU registers are saved, usually on its own stack. On a Cortex-M without an FPU this is about 16 words. Forum guidance for FreeRTOS often quotes roughly 20 words for context as a rough figure.
- Floating-point context. On cores with an FPU, such as Cortex-M4F and M7, a task that uses floating point may need dozens of extra bytes for FPU registers when it’s switched out or interrupted.
- Library functions.
printf,sprintf, and their relatives can use a surprising amount of stack, sometimes hundreds of bytes or more depending on the C library and its configuration. Some math and string functions are also heavier than they look. - Interrupts, on some ports. On Arm Cortex-M ports of the common RTOSes, interrupts run on a separate main stack, not on task stacks. On some other architectures and ports, an interrupt pushes its frame onto whichever task stack is active, so every task needs room for the worst-case interrupt nesting. Check your port’s documentation.
Recursion and variable-length arrays make the worst case hard or impossible to bound, which is why many embedded coding standards discourage or ban them.
Get the units right
The most common sizing mistake is using the wrong unit. A FreeRTOS stack of 1024 on a 32-bit MCU is 4 KB, not 1 KB.
| API | Stack size unit |
|---|---|
FreeRTOS xTaskCreate() (standard kernel) |
Words (StackType_t), so 4 bytes each on 32-bit MCUs |
| FreeRTOS in ESP-IDF | Bytes |
CMSIS-RTOS v2 osThreadNew() |
Bytes |
Zephyr K_THREAD_STACK_DEFINE, K_THREAD_DEFINE |
Bytes |
Eclipse ThreadX tx_thread_create() |
Bytes |
High-water-mark functions generally report in the same units as their API’s stack size. FreeRTOS’s uxTaskGetStackHighWaterMark() returns words on standard ports and bytes in ESP-IDF.
Step 1: start with a generous estimate
Early in development, RAM is usually less scarce than debugging time. Reasonable starting points on a 32-bit microcontroller:
- Simple tasks that toggle pins, wait on a queue, and call a few small functions: often fine with around 512 bytes to 1 KB to start.
- Tasks that format text with
printf-style functions, parse protocols, or call into middleware: start at 2 KB or more. - Tasks running networking, TLS, file systems, or USB stacks: follow the stack’s own documentation, which often calls for several kilobytes.
These are starting guesses, not recommendations for final sizes. The point is to begin well above the real need, then measure down.
Step 2: measure with stack painting
Most RTOSes can fill each stack with a known pattern when the task is created, then later scan from the far end to see how much of the pattern is still intact. The untouched region is the minimum free space the task has ever had: its high-water mark.
FreeRTOS
With INCLUDE_uxTaskGetStackHighWaterMark set to 1:
UBaseType_t uxFree = uxTaskGetStackHighWaterMark(NULL); /* NULL = this task */
A small monitor task can report every task’s figure periodically during testing:
static TaskHandle_t xTasks[] = { /* handles saved from xTaskCreate() */ };
static void vStackMonitorTask(void *pvParameters)
{
(void) pvParameters;
for (;;) {
for (size_t i = 0; i < sizeof(xTasks) / sizeof(xTasks[0]); i++) {
printf("%s: %lu words free\r\n",
pcTaskGetName(xTasks[i]),
(unsigned long) uxTaskGetStackHighWaterMark(xTasks[i]));
}
vTaskDelay(pdMS_TO_TICKS(5000));
}
}
Give the monitor task itself enough stack for printf. RTOS-aware debugger views in STM32CubeIDE, MCUXpresso, SEGGER Ozone, and others also show per-task stack usage without any code.
Zephyr
Enable stack initialization and the thread analyzer in your project configuration:
CONFIG_INIT_STACKS=y
CONFIG_THREAD_STACK_INFO=y
CONFIG_THREAD_ANALYZER=y
CONFIG_THREAD_ANALYZER_AUTO=y
The thread analyzer prints each thread’s stack usage periodically. You can also query one thread with k_thread_stack_space_get().
ThreadX
ThreadX fills thread stacks with a known pattern when they’re created. With stack checking enabled (TX_ENABLE_STACK_CHECKING), the kernel tracks the deepest point reached, and debuggers and the TraceX tool can show per-thread usage. You can also register a callback for stack errors with tx_thread_stack_error_notify().
Make the measurement count
A high-water mark only reflects paths that actually ran. To get a meaningful number:
- Exercise every feature, including error handling, retries, timeouts, and rarely used commands. Error paths often call logging functions with heavy formatting.
- Turn logging up to its most verbose level during the measurement.
- Run under load. Maximum message rates, full queues, and every interrupt source active.
- Include startup and shutdown, firmware update, and configuration changes.
- Measure the build you’ll ship. Optimization level, compiler version, and inlining all change stack use. A debug build at
-O0often uses more stack than a release build, but don’t assume it. Re-measure after any toolchain or optimization change. - Run long enough. Rare combinations of events may take hours to show up.
Step 3: check with static analysis
Testing can miss the deepest path. Static analysis estimates the worst case from the code itself.
With GCC (and Clang), compile with -fstack-usage. The compiler writes a .su file next to each object file, listing the stack frame size of every function:
main.c:42:13:control_update 48 static
comms.c:88:6:parse_frame 216 static
log.c:15:6:log_printf 96 dynamic,bounded
static means the size is fixed. dynamic means it depends on run-time values, such as variable-length arrays or alloca(), and needs closer inspection. The -Wstack-usage=<bytes> option warns about any function whose frame exceeds a limit.
The .su files give per-function sizes, not totals. To find a task’s worst case, you need the call graph: the stack sizes along the deepest chain from the task’s entry function. Open-source scripts and tools can combine .su files with call graph information, and commercial tools such as AbsInt StackAnalyzer analyze the final binary directly. Both approaches have limits:
- Function pointers and callbacks hide call edges, so you may need to annotate them.
- Recursion has no static bound unless you supply one.
- Precompiled libraries may not come with stack usage data.
- Interrupt stacking and the RTOS context must be added separately.
Static analysis and measurement complement each other. If the measured figure is far below the static estimate, check whether your tests reached the deep paths. If the measured figure is above the static estimate, something is missing from the analysis.
Step 4: add a margin
Set each stack to the worst case you found plus a margin for paths you didn’t exercise, future code changes, and toolchain differences. There’s no universal number. Teams commonly use something in the range of 20% to 50% extra, or a fixed minimum of free bytes per task, with larger margins when the worst case came only from testing rather than from analysis. Safety-related projects often have the margin set by their coding or design standard.
Revisit the numbers whenever you add features, change libraries, or update the compiler.
Don’t forget the interrupt (main) stack
On Arm Cortex-M, the common RTOS ports run tasks on the process stack (PSP) and interrupts on the main stack (MSP). After the scheduler starts, the main stack is used for interrupt handlers and some kernel code. That means:
- Task stacks don’t need room for interrupts. This saves RAM across many tasks.
- The main stack must hold the worst case of nested interrupts. That’s every interrupt priority level that can nest, each with its deepest call chain and possibly its FPU context.
- The main stack size is set in the linker script or startup file, not in the RTOS configuration. Vendor templates often use a small default, so check it.
Measure the main stack the same way: fill it with a pattern at startup and check how much remains after a stress test. Some debuggers can do this for you.
Detecting stack overflow at run time
Sizing reduces the risk. Detection tells you when you got it wrong.
FreeRTOS overflow checking
Set configCHECK_FOR_STACK_OVERFLOW in FreeRTOSConfig.h and provide a hook function:
void vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName)
{
(void) xTask;
/* Record pcTaskName somewhere that survives a reset, if you can. */
taskDISABLE_INTERRUPTS();
for (;;) { } /* halt here so a debugger can inspect */
}
- Method 1 (
configCHECK_FOR_STACK_OVERFLOW = 1) checks, at each context switch, whether the saved stack pointer is outside the task’s stack. It’s fast, but it misses an overflow that happened and recovered between switches. - Method 2 (
= 2) also checks that the last bytes at the end of the stack still hold the fill pattern. That catches more cases, at a small extra cost.
Both checks run only at context switches, so they can’t catch every overflow. A badly overflowing task may corrupt memory and crash before the check runs, and the hook may itself fail if memory is already damaged. Treat these checks as a development aid, not a guarantee.
Hardware help: MPU guard regions and stack limit registers
Hardware checks catch an overflow the moment it happens:
- MPU guard regions. A memory protection unit can mark a small region just beyond the end of a stack as inaccessible. Any write into it causes an immediate fault, with the offending code still on the call stack. FreeRTOS MPU ports, Zephyr, and some ThreadX ports support this on suitable hardware.
- Stack limit registers. Cores implementing Armv8-M, such as Cortex-M23, M33, M55, and M85, have stack limit registers (
PSPLIMandMSPLIM). If the stack pointer goes below the limit, the core faults. RTOS ports for these cores commonly set the process stack limit for each task on every context switch, which gives you overflow detection at almost no cost.
If your part supports either feature, enabling it is one of the most valuable things you can do.
Zephyr and ThreadX options
- Zephyr offers
CONFIG_HW_STACK_PROTECTION(MPU guards or stack limit registers where available),CONFIG_STACK_SENTINEL(a software check of a sentinel value at the stack’s end), andCONFIG_STACK_CANARIES. The last uses the compiler’s stack protector, which detects buffer overruns within a function’s frame rather than stack exhaustion. - ThreadX with
TX_ENABLE_STACK_CHECKINGchecks stacks during kernel operations and calls the handler registered withtx_thread_stack_error_notify()when it finds a problem.
Symptoms of a stack overflow
Suspect the stack if you see:
- Hard faults or bus faults with a corrupted or nonsensical call stack in the debugger.
- Variables that change by themselves, especially globals or another task’s data located next to a stack in memory.
- Crashes that appear or disappear when you add a
printf, change optimization, or move code around. - Failures only under load or in rarely used features, such as error handling and verbose logging.
- A task that behaves correctly until a specific input arrives that drives it down a deeper path.
To confirm, enable the strongest detection available, raise every stack substantially, and see whether the problem goes away. If it does, measure the high-water marks to find which task was short.
Ways to reduce stack usage
When RAM is tight:
- Move large buffers off the stack. Make big arrays
static, or allocate them once at startup from a pool. Be careful: astaticbuffer inside a function is shared by every caller, so it’s not safe if several tasks call that function. - Avoid
printfin many tasks. Send log messages to one logging task through a queue, so only that task needs a large stack. Or use a lighter formatting function. - Flatten deep call chains in time-critical or memory-critical tasks, and avoid recursion.
- Pass large structs by pointer, not by value.
- Combine tasks that don’t need to be separate. Each task costs a stack plus a control block, and several small activities can often share one task that waits on a queue.
- Disable floating point in tasks that don’t need it, where your RTOS port allows tasks to opt in to FPU context saving.
For ideas on cutting the number of tasks without losing responsiveness, see real-time scheduling and multitasking in embedded systems. If you’re designing from scratch on a very small part, RTOS vs super loop discusses when one stack is enough.
A stack sizing checklist
- Stack sizes use the right unit for your API (words or bytes).
- Stack painting and high-water-mark reporting are enabled in test builds.
- Every task’s high-water mark was measured on the release build, under load, with all features and error paths exercised.
- Compiler stack usage reports were checked for the deepest call chains, including
dynamicframes. - Each final size includes a deliberate margin.
- The main/interrupt stack was sized and measured separately.
- Overflow detection is enabled: RTOS checks during development, and MPU guards or stack limit registers where the hardware supports them.
- Stack sizes are re-checked after feature additions, library updates, and toolchain changes.
Frequently asked questions
How much margin should I leave?
There’s no single standard. Many teams aim for roughly 20% to 50% above the measured worst case, or a fixed minimum number of free bytes per task, with more margin where the worst case is uncertain. Your project’s coding standard or safety requirements may set the figure for you.
Does a bigger stack slow down context switches?
Generally no. The kernel saves and restores registers, not the whole stack, so stack size doesn’t affect switch time. The cost of a larger stack is RAM, plus any time spent filling it with a pattern at task creation.
Can tasks share stack memory?
Not while they’re running concurrently, since each task needs its own stack to hold its state while it’s switched out. Some designs save RAM by running several short, run-to-completion jobs inside one task, or by using a cooperative or event-driven framework that runs on a single stack.
Should I monitor stacks in production?
It’s often worth it. A low-priority task can check high-water marks occasionally and log or report any task that drops below a threshold. That gives early warning of field conditions your testing didn’t cover. Hardware overflow detection, where available, is also cheap enough to leave on.
Where can I learn the basics of FreeRTOS tasks first?
Our beginner’s FreeRTOS tutorial walks through creating tasks, choosing stack sizes, and checking high-water marks. For how stack units and detection features differ between kernels, see FreeRTOS vs Zephyr vs ThreadX.