Skip to content

Ioto Memory Allocator

Ioto provides a wrapper over the standard malloc memory allocator. This wrapper performs global memory allocation checking and is tailored to the needs of embedded applications.

Memory Allocation

It is difficult and error-prone for programmers to check the result of every API call that can possibly fail due to memory allocation errors. Calls such as strdup and asprintf are often assumed to succeed, but they can, and do fail when memory is depleted.

A better approach is to proactively detect and handle memory allocation errors in one place. The Ioto allocator handles memory allocation errors globally. When Ioto detects a memory allocation failure, it invokes the global memory exception handler. This configurable handler can then decide what is the best course of recovery. The default action is to abort Ioto so that it can be cleanly restarted.

Wrapper Routines

The safe runtime provides three memory allocation routines that wrap the standard libc routines.

  • rAlloc — Allocate memory
  • rFree — Free memory
  • rAllocType — Allocate memory for a given type

The rAlloc routine allocates memory and checks for memory failures and invokes the global exception handler if the memory allocation fails.

The rFree routine frees memory and is NULL tolerant. This routine accepts memory allocated via rAlloc or malloc.

The rAllocType routine is a convenience function to allocate memory for a typed object. For example:

mem = rAllocType(struct shape);

Memory Error Handler

The default memory handler prints a message regarding the memory allocation error and aborts execution.

In many cases, the best recovery is to log the error and quickly reboot the service to minimize down-time. If a slow memory leak is the culprit in your code, then this approach may be sufficient, though clearly not ideal!

You can replace the default handler to perform custom error recovery. Use the rSetMemHandler API to install your own memory handler.

1
2
3
4
5
6
7
void myHandler(int cause, size_t size)
{
    fprintf(stderr, "Memory allocation error for %zd bytes", size);
    //  Try to recover
}

rSetMemoryHandler(myHandler);