FreeRTOS Deep Dive · Part 6 of 8

Stack Sizing & Overflow Detection

FreeRTOS STM32 Intermediate Source Code
FreeRTOS Part 6
FreeRTOS Deep Dive — Part 6
Stack Sizing & Overflow Detection
31:20
Part 6 / 8
31:20
Intermediate
FreeRTOS v10 · STM32F4
01

Overview

Stack overflows are silent killers — they corrupt adjacent memory, crash the system days after the bug was introduced, and are nearly impossible to reproduce without tooling. FreeRTOS provides three detection methods. This part shows how to use all of them and how to measure actual stack usage with high-water marks.

  • Enable stack overflow detection methods 1 and 2
  • Implement vApplicationStackOverflowHook() to catch overflows at runtime
  • Measure real stack usage with uxTaskGetStackHighWaterMark() and right-size stacks
  • Build a monitoring task that reports memory health over UART
02

Detection Methods

🔍
Method 1 — SP Check
After each context switch, checks if the stack pointer passed the boundary. Fast but can miss transient overflows.
configCHECK_FOR_STACK_OVERFLOW = 1
🎨
Method 2 — Paint Pattern
Fills the last 20 stack bytes with a known pattern at creation. Checks the pattern on every context switch — catches far more overflows.
configCHECK_FOR_STACK_OVERFLOW = 2
📊
High Water Mark
Returns the minimum remaining stack in words. Zero means the stack is full. Call after full load testing to right-size every task.
uxTaskGetStackHighWaterMark()
03

Code

01
Overflow hook + watermark monitor
stack_monitor.c
C
#define configCHECK_FOR_STACK_OVERFLOW 2

void vApplicationStackOverflowHook(
    TaskHandle_t xTask, char *pcName)
{
    uart_puts("[FATAL] Stack overflow: ");
    uart_puts(pcName); uart_puts("
");
    taskDISABLE_INTERRUPTS();
    for(;;);
}

TaskHandle_t xSensorH, xProcessH, xStorageH;

void vMonitorTask(void *pv) {
    while(1) {
        uart_printf("Sensor  watermark: %u words
",
            uxTaskGetStackHighWaterMark(xSensorH));
        uart_printf("Process watermark: %u words
",
            uxTaskGetStackHighWaterMark(xProcessH));
        uart_printf("Free heap: %u bytes
",
            xPortGetFreeHeapSize());
        vTaskDelay(pdMS_TO_TICKS(10000));
    }
}
💡
Right-sizing stacks
Run under worst-case load, read each watermark, then keep at least 20% headroom above it. Stack is measured in words (4 bytes each on ARM). A watermark of 50 = 200 bytes remaining.

Continue the Series

Work through all 8 parts of the FreeRTOS Deep Dive to master real-time embedded systems programming.