The allocator interface provides a mechanism to implement own custom allocators that can also be used in many other function in UCX.
A default allocator implementation using the stdlib functions is available via the global symbol cxDefaultAllocator and UCX also provides a memory pool implementation. You are free to add additional own custom implementations. A general sketch that illustrates how to do this can be found below.
The functions cxMalloc(), cxCalloc(), cxRealloc(), cxReallocArray(), and cxFree() invoke the memory management functions specified in the allocator and should behave like their respective stdlibc pendants. Implementations of the allocator interface are strongly encouraged to guarantee this behavior, most prominently that invocations of cxFree() with a NULL-pointer for mem are ignored instead of causing segfault error.
Additionally, UCX provides the functions cxReallocate() and cxReallocateArray(), as well as their independent pendants cx_reallocate() and cx_reallocatearray(). All those functions solve the problem that a possible reallocation might fail, leading to a quite common programming mistake:
// common mistake - mem will be lost hen realloc() returns NULL
mem = realloc(mem, capacity + 32);
if (mem == NULL) // ... do error handling
The above code can be replaced with cx_reallocate() which keeps the pointer intact and returns an error code instead.
// when cx_reallocate() fails, mem will still point to the old memory
if (cx_reallocate(&mem, capacity + 32)) // ... do error handling
Custom Allocator
If you want to define your own allocator, you need to initialize the CxAllocator structure with a pointer to an allocator class (containing function pointers for the memory management functions) and an optional pointer to custom data. An example is shown below:
struct my_allocator_state {
// ... some internal state ...
};
static cx_allocator_class my_allocator_class = {
my_malloc_impl,
my_realloc_impl, // all these functions are somewhere defined
my_calloc_impl,
my_free_impl
};
CxAllocator create_my_allocator(void) {
CxAllocator alloc;
alloc.cl = &my_allocator_class;
struct my_allocator_state *state = malloc(sizeof(*state));
// ... initialize state ...
alloc.data = state;
return alloc;
}
void destroy_my_allocator(CxAllocator *al) {
struct my_allocator_state *state = al->state;
// ... destroy state --
free(state);
}
When you are implementing
Destructor Functions
The allocator.h header also declares two function pointers for destructor functions.
The first one is called simple destructor (e.g. in the context of collections), and the second one is called advanced destructor. The only difference is that you can pass additional custom data to an advanced destructor function.
Destructor functions play a vital role in deep deallocations. Another scenarios, besides destroying elements in a collection, are the deallocation of objects stored in a memory pool or deallocations of deeply nested JSON objects.