</>EmbeddedInterview

How is memory allocated in an RTOS, and why prefer static allocation?

MediumRTOS & Real-Time Systems

Short answer: RTOS objects (task stacks and control blocks, queues, semaphores, timers) can be allocated dynamically from an RTOS heap or statically from memory you provide. Safety-critical and long-running systems prefer static allocation (or allocation only at start-up) because it cannot fail at run time, cannot fragment, is deterministic, and makes RAM usage visible at link time.

FreeRTOS heap schemes

Scheme Free? Coalescing Notes
heap_1 no – allocate only; simplest and deterministic; good for "create everything at start-up"
heap_2 yes no legacy; fragments; avoid
heap_3 yes depends wraps the C library malloc/free with scheduler suspension
heap_4 yes yes first-fit with merging of adjacent blocks; most common
heap_5 yes yes like heap_4 but spans several non-contiguous RAM regions

Static allocation

static StackType_t  sensor_stack[256];
static StaticTask_t sensor_tcb;
TaskHandle_t h = xTaskCreateStatic(sensor_task, "sensor", 256, NULL, 3, sensor_stack, &sensor_tcb);

static uint8_t       q_storage[16 * sizeof(msg_t)];
static StaticQueue_t q_struct;
QueueHandle_t q = xQueueCreateStatic(16, sizeof(msg_t), q_storage, &q_struct);

Enable with configSUPPORT_STATIC_ALLOCATION (and optionally disable dynamic allocation entirely with configSUPPORT_DYNAMIC_ALLOCATION 0).

Guidelines

  • Create all tasks and kernel objects during initialisation; never create/delete them repeatedly at run time.
  • For variable-size application data, use fixed-size memory pools (Zephyr k_mem_slab, ThreadX block pools) instead of a general heap.
  • Monitor the heap (xPortGetMinimumEverFreeHeapSize()) and define vApplicationMallocFailedHook() if any dynamic allocation remains.
  • Make sure the C library's malloc (used by printf, some drivers) is either thread-safe (newlib locks via __malloc_lock) or not used from multiple tasks.