Choosing the right heap scheme helps your program manage memory safely and efficiently. It makes sure your tasks get the memory they need without errors.
Choosing the right heap scheme in FreeRTOS
/* Example: Selecting heap_4.c scheme */ /* Include heap_4.c in your project and define configTOTAL_HEAP_SIZE in FreeRTOSConfig.h */ /* This uses heap_4.c as the heap management scheme */
FreeRTOS provides several heap schemes named heap_1 to heap_5.
You select the scheme by including the corresponding heap_x.c file in your project.
/* Using heap_1.c - Simple, no free */ /* Include heap_1.c in your project */ /* Good for very simple applications with no memory freeing */
/* Using heap_2.c - Allows free but no coalescing */ /* Include heap_2.c in your project */ /* Allows freeing memory but can fragment over time */
/* Using heap_4.c - Best general purpose scheme */ /* Include heap_4.c in your project */ /* Supports malloc, free, and coalescing to reduce fragmentation */
/* Using heap_5.c - Multiple memory regions */ /* Include heap_5.c in your project */ /* Use when you have multiple separate memory areas to manage */
This program selects heap_4 scheme which supports malloc and free with coalescing.
Two tasks allocate and free memory dynamically, printing messages to show success.
/* Example FreeRTOS program using heap_4 scheme */ /* Include heap_4.c in your project and define configTOTAL_HEAP_SIZE in FreeRTOSConfig.h */ #include "FreeRTOS.h" #include "task.h" #include <stdio.h> void vTaskFunction(void *pvParameters) { char *dynamicMemory = (char *)pvPortMalloc(50); if(dynamicMemory != NULL) { snprintf(dynamicMemory, 50, "Task %s allocated memory!", (char *)pvParameters); printf("%s\n", dynamicMemory); vPortFree(dynamicMemory); } else { printf("Memory allocation failed for task %s\n", (char *)pvParameters); } vTaskDelete(NULL); } int main(void) { printf("Starting FreeRTOS heap scheme demo\n"); xTaskCreate(vTaskFunction, "Task1", 1000, "One", 1, NULL); xTaskCreate(vTaskFunction, "Task2", 1000, "Two", 1, NULL); vTaskStartScheduler(); return 0; }
Time complexity of allocation depends on the heap scheme; heap_4 is efficient for most cases.
heap_1 never frees memory, so it can cause memory exhaustion if many allocations happen.
heap_5 is useful for hardware with multiple RAM regions but is more complex to configure.
Choosing the right heap scheme depends on your application's memory usage pattern and hardware.
FreeRTOS offers multiple heap schemes to manage dynamic memory.
heap_4 is the most flexible and commonly used scheme.
Pick the scheme that fits your application's needs for allocation, freeing, and fragmentation control.