Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 37 ยท Memory, Registers and Peripherals

Static Allocation and Memory Pools

Manage memory without malloc: static buffers, fixed-block memory pools, ring buffers for UART data, heap fragmentation and alignment, with runnable C examples.

On a desktop, malloc and free are everyday tools. On a microcontroller with 8 KB of RAM they are a liability: the heap fragments, allocation time is unpredictable, a failure at 3 a.m. in a device in a field has nowhere to report, and a leak of one byte per minute kills the product after a few weeks. Embedded software therefore prefers static allocation, where every buffer exists for the lifetime of the program at a fixed address, and where dynamic behavior is handled with fixed-size pools and ring buffers.

This lesson explains why the heap is risky, then builds the two most useful data structures in firmware: a memory pool of fixed-size blocks and a ring buffer (circular FIFO) for passing data between an interrupt and the main loop.

Why malloc is a risk

  1. Fragmentation. After many allocations and frees of different sizes, free memory is split into small pieces. A request for 100 bytes can fail even though 1,000 bytes are free in total, and nothing can be defragmented because pointers are held by the program.
  2. Non-deterministic timing. Searching free lists takes a variable time, which breaks hard real-time guarantees.
  3. Failure handling. malloc returns NULL; what should an airbag controller do then?
  4. Leaks and double frees that never show up in short tests.
  5. Overhead. Every block has a header of 8 to 16 bytes; tiny allocations waste more than they use.
  6. Reentrancy. The standard malloc is not safe from interrupt handlers.

Coding standards such as MISRA C and the Power of Ten rules (NASA/JPL) prohibit dynamic allocation after initialization. The goal: the worst-case memory use is known at link time. The map file shows the whole budget.

Static allocation

The simplest strategy is to declare everything statically, sized for the worst case:

C
#define MAX_SENSORS 8
static Sensor sensors[MAX_SENSORS];
static uint8_t uart_rx_buffer[128];

Properties: the address is fixed, the size appears in the map file, nothing can fail at run time, and .bss is zeroed for free. The downside is that you pay for the maximum even when unused, and you must decide limits up front. For most embedded systems that is a feature, because it forces you to define requirements ("at most 8 sensors").

Fixed-block memory pools

If you do need to allocate and release objects dynamically (messages, packets, events), use a pool: a static array of equal-sized blocks and a free list. Allocate = pop the first free block; free = push it back. Both operations take constant time, never fragment (all blocks are the same size), and failure is a simple, handleable "pool empty".

The free list can live inside the free blocks themselves: while a block is unused, its first bytes store the index of the next free block.

C A fixed-block memory pool

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The high-water mark tells you after testing whether BLOCK_COUNT was well chosen. RTOSes provide pools and message queues built on the same idea (osPoolAlloc, k_mem_slab in Zephyr, xQueueCreateStatic in FreeRTOS).

Ring buffers

A ring buffer (circular buffer, FIFO) is an array used as a queue: a head index where new data is written and a tail index where data is read; both wrap around at the end. It is the standard way to move bytes between producers and consumers running at different times: a UART receive interrupt writes bytes, the main loop reads them.

flowchart LR
    ISR["UART RX interrupt<br/>push(byte)"] --> RB["Ring buffer<br/>head -> write, tail -> read"]
    RB --> MAIN["Main loop<br/>pop(byte), parse"]

Design choices:

  • One slot wasted vs a count. With only head and tail, head == tail means empty, so a buffer of N slots holds N-1 items (full is head + 1 == tail). Alternatively keep a separate count.
  • Power-of-two size. Wrap with index & (SIZE - 1) instead of the slow %. Use static_assert to enforce the size (compile-time checks).
  • Single producer, single consumer. If only the ISR writes head and only the main loop writes tail, no lock is needed on a CPU where the index accesses are atomic (use volatile or C11 atomics). With multiple producers or consumers you need a critical section.
  • Overrun policy. When full, either drop the new byte (and count the loss), or overwrite the oldest. Never block in an ISR.
C A power-of-two ring buffer with overrun counting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The indices count up forever (they wrap at 2ยณยฒ harmlessly) and only the access is masked. This trick makes "full" (head - tail == SIZE) and "empty" (head == tail) unambiguous, so no slot is wasted, and unsigned subtraction is wrap-safe, as with the millisecond timers in Your First Program: Blinky.

Alignment and placement

  • Allocate buffers for DMA and for 32-bit access aligned (_Alignas(4) or __attribute__((aligned(4)))). A uint8_t array may start at an odd address; casting it to uint32_t * can fault on Cortex-M0.
  • Large constant tables belong in flash (const), and large scratch buffers can sometimes share memory (a union of two exclusive-use buffers) or be placed in a special RAM section with __attribute__((section(".ccmram"))).
  • Check peak use under worst-case load (all inputs active, all interrupts firing) before you trust the budget.

Alternatives when you must be dynamic

  • Arena (bump) allocator: one big buffer and a pointer that only moves forward; free everything at once at the end of a frame or request. Fast and fragmentation-free.
  • Multiple pools of different sizes: 16-, 64-, 256-byte blocks; pick the smallest that fits.
  • Allocate during init only, then freeze: a "no malloc after startup" rule.
  • A real-time allocator such as TLSF (constant-time two-level segregated fit), used in some RTOSes.
C A tiny arena (bump) allocator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main problem of malloc/free on a small MCU over a long run time?

    Different-sized allocations fragment memory, and allocation time and success are not deterministic.
  2. 2. Why is a fixed-block pool free of fragmentation?

    Any freed block can satisfy any later request, so there are no unusable gaps.
  3. 3. In a power-of-two ring buffer with ever-increasing indices, what does head - tail == SIZE mean?

    The difference is the number of stored items; SIZE items means every slot is used.
  4. 4. What is the right action in a UART receive ISR when the ring buffer is full?

    ISRs must be short and non-blocking; record the loss so the application can react.

Summary

  • Prefer static allocation: sizes are known at link time, addresses are fixed and nothing fails at run time.
  • Use fixed-block pools (constant time, no fragmentation, high-water mark) when objects come and go.
  • A ring buffer with power-of-two size and free-running indices passes data between an ISR and the main loop without locks (single producer, single consumer).
  • Decide an overrun policy and count losses; align DMA and 32-bit buffers.
  • Arenas and allocate-once-at-startup are acceptable dynamic alternatives.

Next: ADC and PWM Basics