REALLOCARRAY(3)

NAME
reallocarray - reallocate memory for an array of elements checking for overflow

SYNOPSIS
#include <stdlib.h>
void *
reallocarray(void *ptr, size_t nmemb, size_t size);

DESCRIPTION
The reallocarray() function reallocates the pointer ptr to a size appropriate to handle an allocation of nmemb elements in an array where each of the array elements is size bytes using realloc(3) and making sure that overflow does not happen in the multiplication of “nmemb * size”. Otherwise it behaves like realloc(3).

RETURN VALUES
The reallocarray() function will return NULL if there was overflow or if realloc(3) failed setting errno to ENOMEM or preserving the value from realloc(3).

SEE ALSO
malloc(3), realloc(3), reallocarr(3)

HISTORY
The reallocarray() function first appeared in OpenBSD 5.6. reallocarray() was redesigned in NetBSD 8 as reallocarr(3). Until NetBSD 10, reallocarray was available in the _OPENBSD_SOURCE namespace.

CAVEATS
The reallocarray() function was designed to facilitate safe, robust programming and overcome the shortcomings of the malloc(3) and realloc(3) functions by centralizing the overflow check in the multiplication of nmemb and size.

There are still portability issues. (It does not solve the 0 sized allocation return ambiguity in the C standard: does reallocarray() return NULL or a unique pointer to memory that cannot be accessed? Does a NULL mean that an error occurred, and can someone check errno in that case to find out what happened?) For this reason NetBSD decided to go with an alternative implementation, and created reallocarr(3).