Stack size allocation decides how much memory a task can use for its temporary data. It helps the system run tasks safely without running out of memory.
Stack size allocation in FreeRTOS
xTaskCreate(
TaskFunction_t pvTaskCode,
const char * const pcName,
configSTACK_DEPTH_TYPE usStackDepth,
void *pvParameters,
UBaseType_t uxPriority,
TaskHandle_t *pxCreatedTask
);usStackDepth is the stack size in words, not bytes. For example, on a 32-bit system, 100 means 400 bytes.
Stack size must be enough for the task's needs, including function calls and local variables.
xTaskCreate(
vTaskFunction,
"Task1",
100, // Stack size of 100 words
NULL,
1,
NULL
);xTaskCreate(
vTaskFunction,
"EmptyStack",
0, // Stack size zero (invalid)
NULL,
1,
NULL
);xTaskCreate(
vTaskFunction,
"SmallStack",
10, // Very small stack size
NULL,
1,
NULL
);xTaskCreate(
vTaskFunction,
"LargeStack",
1000, // Large stack size
NULL,
1,
NULL
);This program creates two tasks with different stack sizes. It prints the creation result and simulates running the tasks. The task prints its stack size parameter.
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> void vTaskFunction(void *pvParameters) { int local_array[10]; // Uses some stack printf("Task running with stack size: %d words\n", (int)(intptr_t)pvParameters); vTaskDelete(NULL); // Delete self } int main(void) { BaseType_t result; printf("Creating tasks with different stack sizes...\n"); // Create task with 50 words stack result = xTaskCreate(vTaskFunction, "Task50", 50, (void *)(intptr_t)50, 1, NULL); printf("Task with 50 words stack creation result: %d\n", result); // Create task with 5 words stack (too small) result = xTaskCreate(vTaskFunction, "Task5", 5, (void *)(intptr_t)5, 1, NULL); printf("Task with 5 words stack creation result: %d\n", result); // Start scheduler (in real FreeRTOS, this starts tasks) // Here we just simulate by calling task function directly for demo vTaskFunction((void *)(intptr_t)50); vTaskFunction((void *)(intptr_t)5); return 0; }
Stack size allocation affects how much memory each task uses and prevents crashes from stack overflow.
Time complexity: Setting stack size is a constant time operation during task creation.
Common mistake: Confusing stack size in words vs bytes, leading to too small or too large stacks.
Use larger stack sizes for tasks with deep function calls or large local variables.
Stack size allocation sets how much memory a task can use for temporary data.
It is important to allocate enough stack to avoid crashes but not waste memory.
Stack size is given in words, not bytes, when creating FreeRTOS tasks.