Type

unimemfunc

Memory allocation function.

Since v1.0
typedef void *(*unimemfunc)(void *user_data, void *ptr, size_t old_size, size_t new_size)

Discussion 🔗

Defines the function signature for a custom memory management implementation. The memory manager is responsible for allocating, reallocating, and free’ing memory. The implementation must behave like realloc or free depending upon its arguments.

When new_size is non-zero, the allocator must behave like realloc. If ptr is NULL and old_size is zero, the allocator must behave like malloc.

When new_size is zero, the allocator must behave like free. It must also return NULL to the caller.

A minimal implementation of this function might look like the following. Note this example does not utilize the user_data or old_size parameters.

void *custom_allocf(void *ud, void *ptr, size_t osize, size_t nsize) {
    if (nsize == 0) {
        free(ptr);
        return NULL;
    } else {
        return realloc(ptr, nsize);
    }
}

This code assumes that free(NULL) has no effect and that realloc(NULL,size) is equivalent to malloc(size). ANSI C defines both behaviors.