Skip to content
systemcoding.dev
RTOS

Pass Large Buffers Through a Queue of Pointers Safely

Move large buffers between FreeRTOS tasks and ISRs without copying them: a fixed buffer pool, a queue of small descriptors and a strict one-owner rule.

7 min read
Summarize in AI
Flat illustration of RTOS tasks taking turns on a timeline, with the C, Espressif and Rust logos.

A FreeRTOS queue copies every item, and copying a 1,500-byte network frame twice per hop is wasteful. The standard answer is to queue a pointer instead, and the standard failure is a pointer to memory that is reused, freed twice or modified while someone reads it. This post builds the safe version: a fixed pool of buffers, a small descriptor that travels through the queue and one rule that never bends, that exactly one party owns a buffer at any moment. It includes the free path for when a send fails, a way to detect leaks and a test that proves the pool is balanced. It uses FreeRTOS Kernel V11.3.3. The post on why queues copy data explains the trade-off, and the cornerstone guide on FreeRTOS queues, stream buffers and message buffers shows where this pattern fits among the alternatives.

The design

Three pieces make it work.

  1. A pool. A fixed number of equal-size buffers in static RAM, plus a way to hand them out and take them back. A pool has no fragmentation and a known worst case, which a general heap does not.

  2. A descriptor. A small struct that says where the data is and how much of it is valid. The queue carries descriptors, so each queue operation copies a few bytes, whatever the buffer size.

  3. An ownership rule. A buffer belongs to whoever holds its descriptor. After a successful send, the sender gives up all access. After a receive, the receiver owns the buffer until it returns it to the pool.

The pool

The simplest correct pool is itself a queue: a queue of free buffer pointers. Taking a buffer is a receive from the free queue, and returning one is a send. That reuses the kernel's blocking and its thread safety, and works from interrupts with the FromISR calls.

pool.cc
#include "FreeRTOS.h"
#include "queue.h"

#define POOL_COUNT   8
#define POOL_BUF_LEN 1536

static uint8_t     s_storage[POOL_COUNT][POOL_BUF_LEN] __attribute__((aligned(4)));
static QueueHandle_t xFreeQueue;

void pool_init(void)
{
    xFreeQueue = xQueueCreate(POOL_COUNT, sizeof(uint8_t *));
    configASSERT(xFreeQueue != NULL);

    for (int i = 0; i < POOL_COUNT; i++)
    {
        uint8_t *p = s_storage[i];
        xQueueSend(xFreeQueue, &p, 0);
    }
}

uint8_t *pool_alloc(TickType_t xWait)
{
    uint8_t *p = NULL;
    (void) xQueueReceive(xFreeQueue, &p, xWait);
    return p;                       /* NULL if none arrived within the wait */
}

void pool_free(uint8_t *p)
{
    configASSERT(p >= &s_storage[0][0] && p < &s_storage[POOL_COUNT][0]);
    configASSERT(((p - &s_storage[0][0]) % POOL_BUF_LEN) == 0);

    if (xQueueSend(xFreeQueue, &p, 0) != pdPASS)
    {
        configASSERT(0);            /* the free queue is full: a double free */
    }
}

The two assertions in pool_free catch the most common bugs. A pointer outside the storage array, or one that does not sit on a buffer boundary, was never from this pool. And a failed send to the free queue can only mean it already held every buffer, which is a double free, since the queue has exactly POOL_COUNT slots for POOL_COUNT buffers. A bug that would corrupt memory silently becomes a stop at the line that caused it.

For use from an interrupt, add pool_alloc_isr and pool_free_isr that call xQueueReceiveFromISR and xQueueSendFromISR.

The descriptor and the data queue

descriptor.cc
typedef struct {
    uint8_t *data;
    uint16_t length;
    uint8_t  source;
} frame_t;

static QueueHandle_t xFrameQueue;

void frames_init(void)
{
    xFrameQueue = xQueueCreate(8, sizeof(frame_t));
    configASSERT(xFrameQueue != NULL);
}

frame_t is 8 bytes, so each queue operation copies 8 bytes whether the buffer is 64 or 1,536 bytes long. The queue length of 8 matches the pool size, which means the data queue can never be full when the pool still has buffers to give out, and that makes the send path simple.

The producer

The producer takes a buffer, fills it and sends the descriptor. The key detail is the failure path: if the send fails, the producer still owns the buffer and must return it.

producer.cc
static void vReceiveTask(void *pvParameters)
{
    (void) pvParameters;

    for (;;)
    {
        uint8_t *buf = pool_alloc(pdMS_TO_TICKS(50));
        if (buf == NULL)
        {
            drops_no_buffer++;                   /* pool exhausted: the consumer is behind */
            continue;
        }

        uint16_t n = radio_receive(buf, POOL_BUF_LEN);

        frame_t f = { .data = buf, .length = n, .source = 1 };

        if (xQueueSend(xFrameQueue, &f, pdMS_TO_TICKS(10)) != pdPASS)
        {
            pool_free(buf);                      /* send failed: still ours, give it back */
            drops_queue_full++;
        }
        /* on success the buffer belongs to the consumer: do not touch buf again */
    }
}

The comment on the last line is the rule in one sentence. After a successful send, even reading buf[0] is a bug, because the consumer may already be modifying or freeing it.

The consumer

The consumer receives a descriptor, processes the data and always returns the buffer:

consumer.cc
static void vProcessTask(void *pvParameters)
{
    frame_t f;
    (void) pvParameters;

    for (;;)
    {
        if (xQueueReceive(xFrameQueue, &f, portMAX_DELAY) == pdPASS)
        {
            handle_frame(f.data, f.length);
            pool_free(f.data);                   /* done: back to the pool */
        }
    }
}

There is exactly one pool_free on the consumer path and exactly one on the producer's failure path. Every buffer takes one of two routes, and each route ends in a free.

Reading the state

A pool that runs low is an early warning. A helper to expose the numbers:

pool_stats.cc
UBaseType_t pool_in_use(void)
{
    return POOL_COUNT - uxQueueMessagesWaiting(xFreeQueue);
}

Log the minimum free count over time. A pool whose free count keeps dropping toward zero and does not recover is leaking. The soak-test output:

Text
pool: 8 buffers, min free 5, drops_no_buffer 0, drops_queue_full 0

That is an example of a healthy line: at worst three buffers were in flight, and nothing was dropped. A steadily falling minimum across hours points to a path that forgets to free.

Mistakes the pattern prevents, and ones it does not

The pool-and-descriptor design prevents allocation failure at run time, fragmentation, double free by assertion, and large copies. It does not prevent these:

Touching the buffer after the send. Nothing in C stops you. Make it a habit to null your own pointer immediately: buf = NULL; after a successful send. A later dereference then crashes at once instead of corrupting data.

Freeing a buffer you did not get from the pool. The range assertion catches it.

Holding a buffer too long. A consumer that sits on buffers for a long time starves the pool, and the producer starts dropping. Size the pool for the worst-case number of buffers in flight, including those the consumer holds while it works.

Modifying a buffer that is queued for two consumers. If two tasks need the same data, the design needs a reference count or a copy, since one-owner-at-a-time breaks down. Keep to a single consumer, or have the consumer copy what the other needs.

Cache coherence with DMA. If a DMA engine fills the buffers on a part with data caches, such as Cortex-M7, the buffers must sit in non-cacheable memory or be cleaned and invalidated explicitly.

Choosing the pool size

Count the worst-case buffers simultaneously in use: those being filled by the producer, those waiting in the queue, those being processed by the consumer. With a queue length of 8 and one in each of the other two roles, 10 would be the worst case, and the example's pool of 8 is deliberately tight to make drops visible. Size from your own numbers, then add a margin, and let the counters tell you whether you got it right. The sizing post gives the formulas for the queue length.

When to use something else

If the data is a continuous stream of bytes with one writer and one reader, a stream buffer copies once and needs no pool. If the messages are small and the rate is low, a plain queue copy is simpler and safer. Pointer queues pay off for large frames at high rates, with one producer and one consumer.

The boundary

Everything here assumes a single producer path and a single consumer for each buffer. The kernel protects the queue, and it does not protect the buffer contents, which are plain RAM. The pattern is also only as safe as its discipline, and a codebase where several authors send pointers without a pool will leak. Wrap pool_alloc, the send and pool_free in one module and make the rule part of its documentation.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.