The heap is the portion of memory that is used when a dynamic allocation using malloc is called. It is also where a FreeRTOS task stack and task control block (TCB) are stored when they are created by calling xTaskCreate().
In an MCU FreeRTOS system, there will typically be two heaps created:
- System heap: Defined in the startup and linker scripts described previously. This will not be available for use by the final application code when allocating space for RTOS primitives.
- FreeRTOS heap: Used when creating tasks and other primitives and defined in IncFreeRTOSConfig.h. It can be resized by adjusting the following line:
#define configTOTAL_HEAP_SIZE ((size_t)15360)
Currently, this line is defining a 15 KB heap. This heap must be adequately sized to accommodate the following:
- Stacks (and TCBs) for all tasks that are created using xTaskCreate
- Queues, semaphores, mutexes, event groups, and software timers created using x*Create
Here's a visual representation of where all of the different variables will come from:
There are two possible locations for FreeRTOS primitives and stacks:
- Statically allocated space for a stack and a TCB, passed to a task when calling xTaskCreateStatic()
- Dynamically allocated space for a stack/TCB, created when calling xTaskCreate()
The C heap is only used for any items that are created without the use of the FreeRTOS heap implementation, while the C stack is only used before the scheduler is started, as well as by ISRs. When using an RTOS, it is best to minimize the size of the C heap as much as possible, or entirely. This will leave more available RAM to allocate to the RTOS heap or static variables.