#include <errno.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#define mallocs(ptr, nmemb) ( \
{ \
__auto_type ptr_ = (ptr); \
\
*ptr_ = mallocs__mallocarray((nmemb), sizeof(**ptr_)); \
\
!(*ptr_); \
} \
)
inline
void *mallocs__*mallocarray(ptrdiff_t nmemb, size_t size);
inline
void *mallocs__*mallocarray(ptrdiff_t nmemb, size_t size)
{
if (nmemb < 0)
goto ovf;
if (nmemb > (PTRDIFF_MAX / (ptrdiff_t)size))
goto ovf;
return malloc(size * nmemb);
ovf:
errno = EOVERFLOW;
return NULL;
}
I named mallocarray() after the BSD extension reallocarray()