The RTOS kernel needs RAM each time a task, queue, mutex, software timer, semaphore or event group is created.

The RAM can be automatically dynamically allocated from the RTOS heap within the RTOS API object creation functions, or it can be provided by the application writer.

One embedded / real time system can have very different RAM and timing requirements to another so a single RAM allocation algorithm will only ever be appropriate for a subset of applications.

To get around this problem, FreeRTOS keeps the memory allocation API in its portable layer. The portable layer is outside of the source files that implement the core RTOS functionality, allowing an application specific implementation appropriate for the real time system being developed to be provided.

  • When the RTOS kernel requires RAM, instead of calling malloc(), it calls pvPortMalloc(). When RAM is being freed, instead of calling free(), the kernel calls vPortFree().

The FreeRTOS download includes five sample memory allocation implementations, each of which are described in the following subsections. The subsections also include information on when each of the provided implementations might be the most appropriate to select.

Each provided implementation is contained in a separate source file (heap_1.c, heap_2.c, heap_3.c, heap_4.c and heap_5.c respectively) which are located in the Source/Portable/MemMang directory of the main RTOS source code. Other implementations can be added as needed. Exactly one of these source files should be included in a project at a time [the heap defined by these portable layer functions will be used by the RTOS kernel even if the application that is using the RTOS opts to use its own heap implementation].

  • heap_1 - the very simplest, does not permit memory to be freed.
  • heap_2 - permits memory to be freed, but does not coalescence adjacent free blocks.
  • heap_3 - simply wraps the standard malloc() and free() for thread safety.
  • heap_4 - coalescences adjacent free blocks to avoid fragmentation. Includes absolute address placement option.
  • heap_5 - as per heap_4, with the ability to span the heap across multiple non-adjacent memory areas.

Notes:

  • heap_1 is less useful since FreeRTOS added support for static allocation.
  • heap_2 is now considered legacy as the newer heap_4 implementation is preferred.

Why not use the malloc stuff?

If RTOS objects are created dynamically then the standard C library malloc() and free() functions can sometimes be used for the purpose, but there are some caveats:

  • They are not always available on embedded systems
  • They take up valuable code space
  • They are not thread safe
  • They are not deterministic (the amount of time taken to execute the function will differ from call to call)

so more often than not an alternative memory allocation implementation is required.


🌱 Back to Garden