FreeRTOS Deep Dive · Part 5 of 8

Memory Management & Heap Models

FreeRTOS STM32 Intermediate Source Code
FreeRTOS Part 5
FreeRTOS Deep Dive — Part 5
Memory Management & Heap Models
36:50
Part 5 / 8
36:50
Intermediate
FreeRTOS v10 · STM32F4
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() and vPortFree() 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 regions
heap_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.