Memory areas provide your application with dynamic allocation of fixed-sized memory blocks. Memory areas should be used in preference to the standard C library malloc and free functions if the calling task cannot block or if memory allocation is done by an ISR.

You allocate a memory area by declaring it as a C variable:

CTL_MEMORY_AREA_t m1;

Before using a memory area, you must initialize it using ctl_memory_area_init:

unsigned mem[20];
⁞
ctl_memory_area_init(&m1, mem, 2, 10);

This example uses a 20-element array for the memory area's working storage. The array is split into 10 blocks, each block being two words in size.

To allocate a block from a memory area, use ctl_memory_area_allocate. If the memory block cannot be allocated, zero is returned.

unsigned *block = ctl_memory_area_allocate(&m1);
if (block)
  {
    // Block has been allocated.
  }
else
  {
    // No block has been allocated.
  }

When you have finished with a memory block, use ctl_memory_area_free to return it to the memory area from which it was allocated so it can be reused:

ctl_memory_area_free(&m1, block);

You can associate an event flag with the block available state of a memory queue to wait for a memory block to become available:

CTL_MEMORY_AREA_t m0, m1, m2;
⁞
CTL_EVENT_SET_t e;
⁞
ctl_memory_area_setup_events(&m0, &e, 1<<0);
ctl_memory_area_setup_events(&m1, &e, 1<<1);
ctl_memory_area_setup_events(&m2, &e, 1<<2);
⁞
switch (ctl_events_wait(CTL_EVENT_WAIT_ANY_EVENTS,
                        &e, (1<<0)|(1<<1)|(1<<2),
                        0, 0))
  {
  case 1<<0:
    x = ctl_memory_area_allocate(&m0, …
    break;
  case 1<<1:
    x = ctl_memory_area_allocate(&m1, …
    break;
  case 1<<2:
    x = ctl_memory_area_allocate(&m2, …
    break;
  }

This example sets up and waits for the block-available events of memory areas m0, m1, and m2. When the wait completes, it attempts to allocate memory from the appropriate memory area. Note that you should not use a with-auto-clear event wait type when waiting on events associated with a memory area.