dlindependent_comalloc

Function dlindependent_comalloc 

Source
pub unsafe extern "C" fn dlindependent_comalloc(
    n_element: usize,
    sizes: *const usize,
    chunks: *mut *mut c_void,
) -> *mut *mut c_void
Expand description

independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]);

independent_comalloc allocates, all at once, a set of n_elements chunks with sizes indicated in the “sizes” array. It returns an array of pointers to these elements, each of which can be independently freed, realloc’ed etc. The elements are guaranteed to be adjacently allocated (this is not guaranteed to occur with multiple callocs or mallocs), which may also improve cache locality in some applications.

The “chunks” argument is optional (i.e., may be null). If it is null the returned array is itself dynamically allocated and should also be freed when it is no longer needed. Otherwise, the chunks array must be of at least n_elements in length. It is filled in with the pointers to the chunks.

In either case, independent_comalloc returns this pointer array, or null if the allocation failed. If n_elements is zero and chunks is null, it returns a chunk representing an array with zero elements (which should be freed if not wanted).

Each element must be freed when it is no longer needed. This can be done all at once using bulk_free.

independent_comallac differs from independent_calloc in that each element may have a different size, and also that it does not automatically clear elements.

independent_comalloc can be used to speed up allocation in cases where several structs or objects must always be allocated at the same time. For example:

struct Head { ... }
struct Foot { ... }

void send_message(char*  msg) {
    int msglen = strlen(msg);
    size_t sizes[3] = { sizeof(struct Head), msglen, sizeof(struct Foot) };
    void*  chunks[3];
    if (independent_comalloc(3, sizes, chunks) == 0)
      die();
    struct Head*  head = (struct Head*)(chunks[0]);
    char*         body = (char*)(chunks[1]);
    struct Foot*  foot = (struct Foot*)(chunks[2]);
    // ...
}

In general though, independent_comalloc is worth using only for larger values of n_elements. For small values, you probably won’t detect enough difference from series of malloc calls to bother.

Overuse of independent_comalloc can increase overall memory usage, since it cannot reuse existing noncontiguous small chunks that might be available for some of the elements.