Stack high water mark monitoring helps you see how much stack memory a task uses. It shows the smallest amount of free stack left, so you can avoid running out of memory.
Stack high water mark monitoring in FreeRTOS
UBaseType_t uxTaskGetStackHighWaterMark(TaskHandle_t xTask);
This function returns the minimum amount of stack space that has remained for the task since it started.
The returned value is in words, not bytes. Multiply by sizeof(StackType_t) to get bytes.
UBaseType_t highWaterMark = uxTaskGetStackHighWaterMark(NULL);
UBaseType_t highWaterMark = uxTaskGetStackHighWaterMark(taskHandle);
UBaseType_t highWaterMark = uxTaskGetStackHighWaterMark(NULL); if(highWaterMark == 0) { // Stack overflow likely occurred }
This program creates a task that uses some stack space. It then prints the smallest amount of free stack space left during the task's life.
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> void vExampleTask(void *pvParameters) { volatile int dummyArray[50]; // Use some stack space for(int i = 0; i < 50; i++) { dummyArray[i] = i * i; } UBaseType_t highWaterMark = uxTaskGetStackHighWaterMark(NULL); printf("Stack high water mark (words) for ExampleTask: %u\n", (unsigned int)highWaterMark); vTaskDelete(NULL); } int main(void) { TaskHandle_t exampleTaskHandle = NULL; xTaskCreate(vExampleTask, "ExampleTask", 100, NULL, 1, &exampleTaskHandle); vTaskStartScheduler(); return 0; }
The time complexity of uxTaskGetStackHighWaterMark is O(1) because it returns a stored value.
Space complexity is O(1) as it only reads a variable.
A common mistake is confusing words with bytes; remember to multiply by sizeof(StackType_t) for bytes.
Use this function to check stack usage instead of guessing stack sizes.
Stack high water mark shows the minimum free stack space a task had.
It helps prevent stack overflow by monitoring stack usage.
Use uxTaskGetStackHighWaterMark with the task handle or NULL for current task.