How to understand the return value of uxtaskgetstackhighlwatermark()

1.6k Views Asked by At

According to the official doc <FreeRTOS_Reference_Manual_V10.0.0>: "uxTaskGetStackHighWaterMark() is used to query how close a task has come to overflowing the stack space allocated to it."

I'm using rtl8720, a 32-bits chip running FreeRTOS_v10.2.0. I wrote a test program as follows, and main() function will call TestTaskEntry() :

static void TestStack()
{
    char buff[500] = {0};

    #if defined(INCLUDE_uxTaskGetStackHighWaterMark) && (INCLUDE_uxTaskGetStackHighWaterMark == 1)
    printf("\n\r[2] Min available stack size %d * %d bytes\n\r", uxTaskGetStackHighWaterMark(NULL), sizeof(portBASE_TYPE));
    #endif

    return;
}

static void TestTask()
{
    #if defined(INCLUDE_uxTaskGetStackHighWaterMark) && (INCLUDE_uxTaskGetStackHighWaterMark == 1)
    printf("\n\r[1] Min available stack size %d * %d bytes\n\r", uxTaskGetStackHighWaterMark(NULL), sizeof(portBASE_TYPE));
    #endif

    TestStack();

    #if defined(INCLUDE_uxTaskGetStackHighWaterMark) && (INCLUDE_uxTaskGetStackHighWaterMark == 1)
    printf("\n\r[3] Min available stack size %d * %d bytes\n\r", uxTaskGetStackHighWaterMark(NULL), sizeof(portBASE_TYPE));
    #endif

    vTaskDelete(NULL);
}

void TestTaskEntry(void)
{
    if(xTaskCreate(TestTask, ((const char*)"test task"), 500, NULL,
        tskIDLE_PRIORITY + 3 + PRIORITIE_OFFSET, NULL) != pdPASS) {
        printf("\n\rcreate stack failed\n\r");
    }
}

The printing of the program is as follows:

[1] Min available stack size 485 * 4 bytes

[2] Min available stack size 424 * 4 bytes

[3] Min available stack size 424 * 4 bytes

I think [1] should be closer to the task depth (500 * 4 bytes) of TestTask. But [2] and [3] should be 500 bytes smaller than [1], because there is a local array with a size of 500 bytes. How should I understand the actual execution results of my program? Why is StackHighWater not the smallest remaining stack in TestTask history?

1

There are 1 best solutions below

1
On BEST ANSWER

I think your buff variable is optimized by the compiler because it is never used, so it does not need any stack. You can try to prevent optimization by writing volatile char buff[500] = {0};. For testing purposes, I would also increase the stack size when calling xTaskCreate.

There is also a remarkable chapter for stack usage estimation in the FAQ: https://www.freertos.org/FAQMem.html#StackSize