Static and dynamic allocation decide how memory is given to tasks in FreeRTOS. Static allocation uses fixed memory, while dynamic allocation gets memory when needed.
Static vs dynamic allocation (configSUPPORT_STATIC_ALLOCATION) in FreeRTOS
/* Enable static allocation in FreeRTOSConfig.h */ #define configSUPPORT_STATIC_ALLOCATION 1 /* Create task with static allocation */ StaticTask_t xTaskBuffer; StackType_t xStack[configMINIMAL_STACK_SIZE]; TaskHandle_t xTaskHandle; xTaskHandle = xTaskCreateStatic( TaskFunction, // Task function "TaskName", // Name configMINIMAL_STACK_SIZE, // Stack size NULL, // Parameters tskIDLE_PRIORITY, // Priority xStack, // Stack buffer &xTaskBuffer // Task buffer );
Static allocation requires you to provide memory buffers for the task's stack and control block.
Dynamic allocation uses heap memory and is enabled by configSUPPORT_DYNAMIC_ALLOCATION.
/* Static allocation example */ StaticTask_t myTaskBuffer; StackType_t myStack[100]; TaskHandle_t myTaskHandle = xTaskCreateStatic( MyTaskFunction, "MyTask", 100, NULL, 1, myStack, &myTaskBuffer );
/* Dynamic allocation example */ TaskHandle_t myTaskHandle; xTaskCreate( MyTaskFunction, "MyTask", 100, NULL, 1, &myTaskHandle );
This program creates a FreeRTOS task using static allocation and starts the scheduler. The task prints a message every second.
#include "FreeRTOS.h" #include "task.h" #include <stdio.h> /* Task function */ void vTaskCode(void * pvParameters) { for(;;) { printf("Task running\n"); vTaskDelay(pdMS_TO_TICKS(1000)); } } int main(void) { /* Enable static allocation in FreeRTOSConfig.h before compiling */ static StaticTask_t xTaskBuffer; static StackType_t xStack[configMINIMAL_STACK_SIZE]; TaskHandle_t xHandle = xTaskCreateStatic( vTaskCode, "StaticTask", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, xStack, &xTaskBuffer ); if (xHandle == NULL) { printf("Task creation failed\n"); return 1; } vTaskStartScheduler(); /* Should never reach here */ return 0; }
Static allocation avoids runtime heap usage, which is safer for embedded systems.
Dynamic allocation is easier but can cause fragmentation and unpredictable failures.
configSUPPORT_STATIC_ALLOCATION must be set to 1 in FreeRTOSConfig.h to use static allocation.
Static allocation uses fixed memory buffers you provide for tasks.
Dynamic allocation uses heap memory managed by FreeRTOS at runtime.
Static allocation is safer and more predictable for embedded real-time systems.