Memory and stack management
Every task needs a stack size, and when one overflows it corrupts another task's memory. How to measure stack use and catch overflows.
Every task has a stack
The 256 in xTaskCreate(..., 256, ...) is in words (4 bytes), so it is 1 KB. Ten tasks use 10 KB on stacks alone. Call depth, local arrays and printf (which often uses 1 KB or more) eat stack.
Measuring how much is used
UBaseType_t left = uxTaskGetStackHighWaterMark(NULL); // smallest amount left (words)
Run every feature at its heaviest, look at what is left, and set the size at 1.5 to 2 times the usage.
RoadmapSee where this note sits in RTOS→Overflow detection
#define configCHECK_FOR_STACK_OVERFLOW 2
void vApplicationStackOverflowHook(TaskHandle_t t, char *name) { /* log and halt */ }
Method 2 writes a pattern at the end of the stack and checks it on every context switch. Cortex-M33 and later can catch it immediately with the hardware stack-limit register (PSPLIM).
Heap
FreeRTOS objects (tasks, queues, semaphores) are created from the FreeRTOS heap by default.
| Heap implementation | Characteristics |
|---|---|
| heap_1 | Allocate only, no free. Safest for systems that create everything at start-up and are done |
| heap_4 | Can free, merges adjacent blocks. General purpose |
The static allocation API (xTaskCreateStatic) fixes memory at compile time with no heap at all, which is why safety-related products prefer it.