Search code examples
stackoverflowqemufreertos

freertos stack does not overflow


Hello good people of internet

I was studying FreeRTOS, I expect myTaskA to overflow the stack but it does not. How come?

FreeRTOSConfig.h

#define configCHECK_FOR_STACK_OVERFLOW           2
// demo 2 : allocating huge array in stack to ovf
static void app_myTaskA( void * pvParameters ) {
    uint32_t myHugeArray[APP_DEFAULT_STACK_SIZE+1];
    printf("remStack: %d\n", (int)uxTaskGetStackHighWaterMark(NULL));
    uint32_t anotherU32 = 0;
    printf("remStack: %d\n", (int)uxTaskGetStackHighWaterMark(NULL));

    for(size_t i = 0; i < sizeof(myHugeArray); ++i) {
        // implementing sth so compiler does not optimize out
        myHugeArray[i] = i;
        myHugeArray[i]++;
        myHugeArray[i]--;
        anotherU32++;
    }

    while(1) { // to see if task survives and prints remaining stack constantly
        int remStack = (int)uxTaskGetStackHighWaterMark(NULL);
        if (remStack) {
            printf("remStack: %d\n", remStack);
        } else {
            printf("no remStack\n");
        }
    }
}

Terminal Output

QEMU_started
remStack: 1014
remStack: 1014
no remStack
no remStack
no remStack

Solution

  • The function call (int)uxTaskGetStackHighWaterMark(NULL) (GitHub link) does not make a callback into OS internals. No checking is therefore performed and the task never returns from the loop.

    If you return from the task or call another OS function, that will mack a callback to OS (possibly resource handling calls), then the OS will call the OS checking logic.

    Same also when the task will get preempted by another task.