FreeRTOS Deep Dive · Part 5 of 8
Memory Management & Heap Models
36:50
Part 5 / 8
🧠 FreeRTOS Deep Dive Series · 8 Parts
Part 5 of 8
Part 01
Scheduler, Priorities & Context Switch
55:30
Part 02
Task Notifications vs Event Groups
38:15
Part 03
Software Timers & Idle Hook Patterns
29:44
Part 04
Queues, Semaphores & Mutexes
42:18
Part 05
Memory Management & Heap Models
36:50
Part 06
Stack Sizing & Overflow Detection
31:20
Part 07
Low-Power RTOS & Tickless Idle
44:05
Part 08
Debugging & Trace with Tracealyzer
50:40
01
Overview
FreeRTOS ships five heap implementations. Picking the wrong one causes non-deterministic allocation times or fragmentation that silently bricks devices after weeks of uptime. This part demystifies heap_1 through heap_5 and shows how to monitor free memory at runtime.
- Understand when each heap model is appropriate
- Use
pvPortMalloc()andvPortFree()safely - Monitor heap health at runtime with
xPortGetFreeHeapSize() - Span multiple SRAM regions with heap_5 for MCUs with CCMRAM or external PSRAM
02
The Five Heap Models
1
heap_1 — Allocate only
Memory is never freed. O(1) allocation. Deterministic. Use when all objects created at startup and never destroyed — ideal for safety-critical systems.
No free · Deterministic · Smallest code
3
heap_3 — Wrap malloc/free
Wraps the compiler's standard malloc/free with scheduler suspension. Heap size set by linker. Non-deterministic allocation time.
Uses toolchain malloc · Non-deterministic
4
heap_4 — Best-fit + coalescence ★
Merges adjacent free blocks to reduce fragmentation. Single contiguous array. The most commonly used model — a good default for most projects.
Coalescing · Single region · Recommended
5
heap_5 — Multiple regions
Like heap_4 but spans non-contiguous memory regions. Use when your MCU has internal SRAM plus CCMRAM or external PSRAM.
Multi-region · Coalescing · Most flexible
03
Code
01
heap_5 spanning two SRAM regionsheap_init.c
C
static uint8_t ucHeap1[64*1024] __attribute__((section(".dtcmram"))); static uint8_t ucHeap2[128*1024] __attribute__((section(".sram1"))); void Heap_Init(void) { const HeapRegion_t regions[] = { { ucHeap1, sizeof(ucHeap1) }, { ucHeap2, sizeof(ucHeap2) }, { NULL, 0 } }; vPortDefineHeapRegions(regions); } void vMemMonitor(void *pv) { while(1) { size_t free = xPortGetFreeHeapSize(); size_t min = xPortGetMinimumEverFreeHeapSize(); if(free < 2048) Error_Handler(ERR_LOW_HEAP); vTaskDelay(pdMS_TO_TICKS(5000)); } }
Continue the Series
Work through all 8 parts of the FreeRTOS Deep Dive to master real-time embedded systems programming.