DOKK / manpages / debian 10 / libbsd-dev / reallocarray.3bsd.en
REALLOCARRAY(3bsd) 3bsd REALLOCARRAY(3bsd)

reallocarraymemory allocation and deallocation

library “libbsd”

#include <stdlib.h> (See libbsd(7) for include usage.)
void *
reallocarray(void *ptr, size_t nmemb, size_t size);

When using () be careful to avoid the following idiom:

if ((p = malloc(num * size)) == NULL)
	err(1, "malloc");

The multiplication may lead to an integer overflow, which can be avoided using the extension (), as follows:

if ((p = reallocarray(NULL, num, size)) == NULL)
	err(1, "malloc");

Alternatively () is a more portable solution which comes with the cost of clearing memory.

If () must be used, be sure to test for overflow:

if (size && num > SIZE_MAX / size) {
	errno = ENOMEM;
	err(1, "overflow");
}

The use of () or calloc() is strongly encouraged when allocating multiple sized objects in order to avoid possible integer overflows.

The reallocarray() function returns a pointer to the allocated space if successful; otherwise, a null pointer is returned and errno is set to ENOMEM.

malloc(3), calloc(3), alloca(3)

reallocarray() appeared in OpenBSD 5.6, glibc 2.26.

May 1, 2014 Debian