fxlibc/src/stdlib/reallocarray.c

24 lines
758 B
C

#include <stdlib.h>
#include <errno.h>
/*
** The reallocarray() function changes the size of the memory block pointed to
** by ptr to be large enough for an array of nmemb elements, each of which is
** size bytes. It is equivalent to the call: `realloc(ptr, nmemb * size);`
**
** However, unlike that realloc() call, reallocarray() fails safely in the case
** where the multiplication would overflow. If such an overflow occurs,
** reallocarray() returns NULL, sets errno to ENOMEM, and leaves the original
** block of memory unchanged.
*/
void *reallocarray(void *ptr, size_t nmemb, size_t size)
{
unsigned int total_size;
if(__builtin_umul_overflow(nmemb, size, &total_size)) {
errno = ENOMEM;
return NULL;
}
return (realloc(ptr, total_size));
}