Passing auto variables defined in main as task parameters

A basic freeRTOS code looks something like:

int main(void) {
xTaskCreate(…);

vTaskStartScheduler();

for(;;) {
    //Never reaches here unless memory issue
}

}

Once the scheduler starts, the scheduler switches between tasks, never returning to the main function.
Now, if I have a variable defined inside main and I pass it as a task parameter.

  1. Will it cause a dangling pointer issue? If my main never returns, why would the memory location become invalid?

Eg:

int main(void) {
int count = 0;

xTaskCreate( taskFunction, "Task1", 200, (void*)&count, 1, taskHandle);

vTaskStartScheduler();

for(;;) {
    //Never reaches here unless memory issue
}

}

See this page: https://www.freertos.org/FAQHelp.html and search for “main() stack” for details.
In this particular case a FreeRTOS application might not be fully C/C++ compliant when starting the OS runtime and switching over the processor to a different (HW) stack.

1 Like

We looked at what the c standard says on this one, and it is something like the main() stack has to remain valid while it is still in context, so it’s subjective as to whether when it no longer in use (as each task has its own stack) if it is considered still in context.

@rtel Well… yes, I’m also not super happy with the statement that a FreeRTOS application might not be fully C/C++ compliant during the transition from a bare C program to a multi-tasking FreeRTOS application running a scheduler and a bunch of tasks.
I just tried to express in an easy to understand way that vTaskStartScheduler is not just a simple C-function call even if it looks like that and might have non-obvious side effects like resetting the main stack.
I’m sure there is a better wording for that :wink:
The initial main program could be considered as a completely separate boot loader for a FreeRTOS application. But that’s far too strict and also misleading because it’s a common paradigm to allocate some FreeRTOS resources and at least one task before starting the scheduler …

So is this detailed in the FreeRTOS reference manual? I think maybe not because it seems to depend on the particular port. It would seem, since FreeRTOS is open source, that one could modify the offending port to NOT play the “recycle the startup main() stack” trick, thereby making it Fully C/C++ compatible. Of course, you will need a bigger stack for the startup main() function in that case, and you will not reclaim it, so you will use some additional ram in your running application.

Yes, you can. These lines recycle the main stack - FreeRTOS-Kernel/port.c at main · FreeRTOS/FreeRTOS-Kernel · GitHub