0
0
FreeRTOSprogramming~5 mins

Stack high water mark monitoring in FreeRTOS

Choose your learning style9 modes available
Introduction

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.

When you want to check if a task's stack size is enough during development.
When debugging a task that crashes or behaves oddly due to stack overflow.
When optimizing memory usage in a system with many tasks.
When you want to monitor stack usage over time to detect leaks or growth.
When testing new code to ensure it does not use excessive stack.
Syntax
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.

Examples
Get the high water mark for the current task.
FreeRTOS
UBaseType_t highWaterMark = uxTaskGetStackHighWaterMark(NULL);
Get the high water mark for a specific task using its handle.
FreeRTOS
UBaseType_t highWaterMark = uxTaskGetStackHighWaterMark(taskHandle);
If the high water mark is zero, the task likely used all its stack space.
FreeRTOS
UBaseType_t highWaterMark = uxTaskGetStackHighWaterMark(NULL);
if(highWaterMark == 0) {
    // Stack overflow likely occurred
}
Sample Program

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.

FreeRTOS
#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;
}
OutputSuccess
Important Notes

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.

Summary

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.