Search code examples
c++crtosfreertos

Main stack space and task stack space


I want to know if there any difference between main stack space and a task's stack space. I have taken up a quiz on RTOS in which the following question was asked

Suppose there is a non static local variable declared in the task function, where exactly the memory for the non static variable is allocated during the execution of task function ?

void task_function(void *p)

{

 /*this is task function */

int i ; /* non static variable */
}

The options given were: a. Main stack space of RAM. b.Task's stack space.

I want to know if there is a separate main stack space of RAM other than the stack space allocated for each task. And if it is then why?


Solution

  • Upon startup, there is startup code that runs before main gets called. The startup code puts in place the run-time environment that is required by main. This includes initializing initialized variables, zeroing out uninitialized variables, setting the stack pointer, and, for C++, calling the constructors for statically allocated objects. So when main gets called there is already a stack setup and in use. I presume this is what the quiz refers to as the "main stack".

    For Free-RTOS and other typical RTOS, the RTOS is not setup and running when main is called. Rather, that is typically done within main by calling xTaskCreate and then vTaskStartScheduler. Each time main calls xTaskCreate it creates a task and assigns a stack space for that task. But while main is running it is still using the original stack created by the startup code. Once vTaskStartScheduler is called, the RTOS scheduler will perform a context switch to one of the tasks. The context switch includes changing the stack pointer to the task's stack. So when the task starts executing it uses it's own stack.

    So yes, there is a main stack space that is separate from the tasks' stack spaces. It is necessary so that main can do everything that it does before starting the RTOS scheduler.