FreeRTOS Deep Dive · Part 6 of 8
Stack Sizing & Overflow Detection
31:20
Part 6 / 8
🧠 FreeRTOS Deep Dive Series · 8 Parts
Part 6 of 8
Part 01
Scheduler, Priorities & Context Switch
55:30
Part 02
Task Notifications vs Event Groups
38:15
Part 03
Software Timers & Idle Hook Patterns
29:44
Part 04
Queues, Semaphores & Mutexes
42:18
Part 05
Memory Management & Heap Models
36:50
Part 06
Stack Sizing & Overflow Detection
31:20
Part 07
Low-Power RTOS & Tickless Idle
44:05
Part 08
Debugging & Trace with Tracealyzer
50:40
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 monitorstack_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.