Skip to content
Skills Library
Programming · Building & coding

memory-mgmt-patterns

/memory-mgmt-patterns

Deterministic memory patterns: static FreeRTOS objects, pools for variable-rate messages, heap statistics, stack high-water mark audits, and placing arrays in specific SRAM regions. Use when removing malloc from firmware or tracking down memory exhaustion.

Licence
MIT
Last repository change
09.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 09.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Deterministic memory patterns: static FreeRTOS objects, pools for variable-rate messages, heap statistics, stack high-water mark audits, and placing arrays in specific SRAM regions. Use when removing malloc from firmware or tracking down memory exhaustion.

Original author description

Deterministic memory patterns: static FreeRTOS objects, pools for variable-rate messages, heap statistics, stack high-water mark audits, and placing arrays in specific SRAM regions. Use when removing malloc from firmware or tracking down memory exhaustion.

How it works

  1. Knowledge Base
  2. Pattern 1: Static FreeRTOS Objects
  3. Pattern 2: Memory Pool for Variable-Frequency Messages
  4. Pattern 3: Heap Statistics Monitoring
  5. Pattern 4: Stack High-Water Mark Audit
  6. Pattern 5: Placing Arrays in Specific SRAM Regions
  7. Anti-Patterns
  8. References
Original SKILL.md headings · 188 lines, 592 words
SKILL.md preview
---
name: "memory-mgmt-patterns"
description: "Deterministic memory patterns: static FreeRTOS objects, pools for variable-rate messages, heap statistics, stack high-water mark audits, and placing arrays in specific SRAM regions. Use when removing malloc from firmware or tracking down memory exhaustion."
---

# memory-mgmt-patterns

## Knowledge Base

Embedded memory management patterns for deterministic, fragmentation-free firmware.

---

## Pattern 1: Static FreeRTOS Objects

Avoid dynamic allocation for RTOS objects. All objects pre-allocated at compile time.

```c
/* Static task */
static StackType_t  s_sensor_stack[256];
static StaticTask_t s_sensor_tcb;
static TaskHandle_t s_sensor_handle;

/* Static queue: 8 messages of 16 bytes each */
static uint8_t          s_queue_storage[8 * 16];
static StaticQueue_t    s_queue_struct;
static QueueHandle_t    s_queue;

/* Static semaphore */
static StaticSemaphore_t s_sem_struct;
static SemaphoreHandle_t s_sem;

void rtos_objects_create(void)
{
    s_sensor_handle = xTaskCreateStatic(
        sensor_task, "sensor",
        256U, NULL, TASK_PRIO_SENSOR,
        s_sensor_stack, &s_sensor_tcb);
    configASSERT(s_sensor_handle != NULL);

    s_queue = xQueueCreateStatic(8, 16, s_queue_storage, &s_queue_struct);
    configASSERT(s_queue != NULL);

    s_sem = xSemaphoreCreateBinaryStatic(&s_sem_struct);
    configASSERT(s_sem != NULL);
}
```

Required in `FreeRTOSConfig.h`: `configSUPPORT_STATIC_ALLOCATION 1`.

---

## Pattern 2: Memory Pool for Variable-Frequency Messages

When messages arrive at variable rate, a pool prevents heap fragmentation:

```c
/* Message pool: 32 messages, 128 bytes each */
typedef struct {
    uint8_t  data[120];
    uint8_t  len;
    uint8_t  type;
    uint16_t seq;
} msg_t;

#define MSG_POOL_SIZE 32U
static msg_t      s_msg_pool[MSG_POOL_SIZE];
static uint32_t   s_pool_used_mask = 0U;  /* Bitmask: bit N = msg N is in use */

msg_t *msg_alloc(void)
{
    taskENTER_CRITICAL();
    for (uint32_t i = 0; i < MSG_POOL_SIZE; i++) {
        if (!(s_pool_used_mask & (1U << i))) {
            s_pool_used_mask |= (1U << i);
            taskEXIT_CRITICAL();
            return &s_msg_pool[i];
        }
    }
    taskEXIT_CRITICAL();
    return NULL;  /* Pool exhausted: caller must handle */
}

void msg_free(msg_t *m)
{
    uint32_t idx = (uint32_t)(m - s_msg_pool);
    configASSERT(idx < MSG_POOL_SIZE);
    taskENTER_CRITICAL();
    s_pool_used_mask &= ~(1U << idx);
    taskEXIT_CRITICAL();
}
```

---

## Pattern 3: Heap Statistics Monitoring

```c
/* Log heap stats periodically for detecting slow leak */
void heap_monitor_task(void *param)
{
    (void)param;
    HeapStats_t stats;

    for (;;) {
        vPortGetHeapStats(&stats);

        char buf[128];
        snprintf(buf, sizeof(buf),
            "HEAP free=%lu min=%lu blocks=%lu",
            (unsigned long)stats.xAvailableHeapSpaceInBytes,
            (unsigned long)stats.xMinimumEverFreeBytesRemaining,
            (unsigned long)stats.xNumberOfFreeBlocks);
        log_info(buf);

        /* Alert if heap falls below 2KB */
        if (stats.xAvailableHeapSpaceInBytes < 2048U) {
            log_error("HEAP LOW");
        }

        vTaskDelay(pdMS_TO_TICKS(30000));  /* Every 30 seconds */
    }
}
```

`xMinimumEverFreeBytesRemaining` is the all-time low-water mark — use it for sizing.

---

## Pattern 4: Stack High-Water Mark Audit

```c
/* Call from a debug task or startup once system is stable */
void task_stack_audit(void)
{
    typedef struct {
        const char  *name;
        TaskHandle_t handle;
        uint32_t     min_expected_words;
    } task_entry_t;

    const task_entry_t tasks[] = {
        { "sensor",  s_sensor_handle,  32U },
        { "comm",    s_comm_handle,    64U },
        { "display", s_display_handle, 48U },
    };

    for (uint32_t i = 0; i < sizeof(tasks)/sizeof(tasks[0]); i++) {
        UBaseType_t hwm = uxTaskGetStackHighWaterMark(tasks[i].handle);
        if (hwm < tasks[i].min_expected_words) {
            /* Stack is close to overflow: increase allocation */
            configASSERT(0);  /* Break in debugger */
        }
    }
}
```

---

## Pattern 5: Placing Arrays in Specific SRAM Regions

```c
/* STM32F4: CCM RAM (0x10000000, 64KB) — no DMA access, CPU-only, fastest */
__attribute__((section(".ccm")))
static float s_fft_buffer[1024];   /* 4KB in CCM */

/* STM32F4: SRAM2 (0x2001C000, 16KB) — DMA-accessible backup */
__attribute__((section(".sram2")))
static uint8_t s_dma_rx_buf[4096];

/* Core-coupled memory for FreeRTOS idle task stack (avoids main SRAM contention) */
__attribute__((section(".ccm")))
static StackType_t s_idle_stack[configMINIMAL_STACK_SIZE];
```

Requires corresponding sections in linker script targeting the CCM/SRAM2 MEMORY regions.

---

## Anti-Patterns

- **Calling `malloc` in ISR**: `malloc` is not reentrant and not interrupt-safe. Use a pool.
- **Not checking `pvPortMalloc` return value**: returns NULL on heap exhaustion. Dereferencing NULL = HardFault.
- **Single heap_4 spanning all SRAM**: if DMA buffers and task stacks share one heap, a DMA overrun can corrupt task stacks silently.
- **Stack too small with `printf`**: `printf` with float formatting (`%f`) uses ~1KB of stack. Use integer formatting in embedded code.

## References

- FreeRTOS Heap: freertos.org/a00111.html
- ARM MPU: ARM Cortex-M4 Generic User Guide, Chapter 4.5
- FreeRTOS `uxTaskGetStackHighWaterMark`: freertos.org/uxTaskGetStackHighWaterMark.html

Versions

The database has no other skills named memory-mgmt-patterns.

Database snapshot: 13.11.2026 · package version 3bd2c3c45f1f (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 90memory-budgeting
    Use when Arduino or embedded projects hit SRAM, flash, heap, stack, partition, JSON-buffer, or performance limits, or when reviewing String use, F() placement, OTA slots, FreeRTOS stacks, or memory margin.
  • 100freertos-patterns
    Use when users need ESP32 FreeRTOS or RP2040 multicore patterns for task creation, queues, synchronization, memory checks, task notifications, or cross-core coordination.
  • 100esp32-arduino-embedded-c
    Guidance for production-grade ESP32 Arduino and Embedded C/C++ development. Use when building firmware for ESP32, ESP32-S3, or ESP32-C3 microcontrollers, optimizing FreeRTOS tasks, managing SRAM/PSRAM, writing ISR-safe code, or handling dual-core concurrency and hardware peripherals.
  • 100meddev-memory-management
    Ensure deterministic and safe memory usage: static allocation, pools, stack sizing, MPU usage, and corruption detection for medical device firmware. Use when working on memory management in medical device software.
  • 90freertos-stack-overflow-task-sizing
    Use when a task panics, corrupts adjacent memory or fails only with large payloads or verbose logging. Establish target-specific constraints, evidence, failure analysis and measurable verification before release.
  • 100memory-audit
    Audit embedded code for stack overflow risks, heap fragmentation, static allocation patterns, and memory leaks. Use when investigating OOM crashes, optimizing memory usage, or reviewing memory-critical code on constrained devices.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.