Search topics...
Operating Systems & RTOSMemory Managementintermediate

How is memory managed in an RTOS and why is heap fragmentation a concern?

0 upvotes
Practice with AISoon
Study the fundamentals first — Operating Systems & RTOS topic page

In desktop systems, dynamic memory allocation (malloc/free) is used freely. In embedded RTOS systems, dynamic allocation is used cautiously because of fragmentation, non-deterministic timing, and limited RAM.

Heap fragmentation occurs when repeated allocations and frees of different sizes create small, non-contiguous free blocks in the heap. Even if the total free memory is sufficient, no single block may be large enough to satisfy a new allocation request. On a desktop with gigabytes of RAM, this is manageable. On an MCU with 64 KB of RAM, fragmentation can cause allocation failures that are nearly impossible to reproduce and debug. FreeRTOS provides multiple heap implementations to address this: heap_1 (allocate only, never free — simplest and deterministic), heap_2 (best-fit with free, but no coalescing — fragments over time), heap_4 (first-fit with coalescing — better for mixed allocation sizes), and heap_5 (like heap_4 but spans non-contiguous memory regions).

Best practices in embedded memory management include: allocate all dynamic objects (tasks, queues, semaphores) at startup and never free them; use statically allocated objects when possible (xTaskCreateStatic in FreeRTOS); use fixed-size memory pools (block allocators) instead of general-purpose heaps for objects that are allocated and freed frequently; and avoid malloc/free entirely in safety-critical systems (MISRA C forbids dynamic memory after initialization). An interview may ask: "Is it safe to call malloc from an ISR?" The answer is no — malloc is not reentrant (it uses global data structures) and may block (if the heap is protected by a mutex).

Source: Operating Systems & RTOS Q&A