Compat
Overflow-checked array allocation used by the containers. Linux, macOS, OpenBSD, and FreeBSD all compile the local function in src/compat.c. None of them call the system reallocarray.
Usage#
Call lf_reallocarray() with the element count and element size. Pass NULL to allocate a new array.
int *values = lf_reallocarray(NULL, 16, sizeof(int));
if (values != NULL) {
int *grown = lf_reallocarray(values, 32, sizeof(int));
if (grown != NULL) {
values = grown;
}
free(values);
}
For a nonzero allocation size, a failed call leaves the original allocation yours to free. Store the result in a temporary pointer when growing an existing array.
Functions#
lf_reallocarray#
Reallocates memory for nmemb elements of size bytes each. If nmemb * size would overflow size_t, the call returns NULL, sets errno to ENOMEM, and does not call realloc. Otherwise it returns realloc(ptr, nmemb * size). When that product is nonzero, allocation failure returns NULL and sets errno to ENOMEM. A zero count or element size follows the platform's realloc(ptr, 0) behavior.
The lf_ prefix keeps the symbol off the system reallocarray from libc, libbsd, or the SDK. The body is this local check on every supported platform.
void *lf_reallocarray(void *ptr, size_t nmemb, size_t size);