From: Todd C. Miller Date: Fri, 30 Mar 2012 18:55:02 +0000 (-0400) Subject: Add ecalloc(). X-Git-Tag: SUDO_1_7_9p1~13 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=f0b706986dad139f04ca1cb7125d4bd290432a8e;p=sudo Add ecalloc(). --HG-- branch : 1.7 --- diff --git a/alloc.c b/alloc.c index 535465c4a..fc04da584 100644 --- a/alloc.c +++ b/alloc.c @@ -106,6 +106,31 @@ emalloc2(nmemb, size) return ptr; } +/* + * ecalloc() allocates nmemb * size bytes and exits with an error + * if overflow would occur or if the system malloc(3) fails. + * On success, the allocated space is zero-filled. + */ +void * +ecalloc(nmemb, size) + size_t nmemb; + size_t size; +{ + void *ptr; + + if (nmemb == 0 || size == 0) + errorx(1, "internal error, tried to ecalloc(0)"); + if (nmemb != 1) { + if (nmemb > SIZE_MAX / size) + errorx(1, "internal error, ecalloc() overflow"); + size *= nmemb; + } + if ((ptr = malloc(size)) == NULL) + errorx(1, "unable to allocate memory"); + memset(ptr, 0, size); + return ptr; +} + /* * erealloc() calls the system realloc(3) and exits with an error if * realloc(3) fails. You can call erealloc() with a NULL pointer even diff --git a/alloc.h b/alloc.h index d3e1b07de..6f11cb748 100644 --- a/alloc.h +++ b/alloc.h @@ -22,6 +22,7 @@ int easprintf(char **, const char *, ...) __printflike(2, 3); int evasprintf(char **, const char *, va_list) __printflike(2, 0); void efree(void *); +void *ecalloc(size_t, size_t); void *emalloc(size_t); void *emalloc2(size_t, size_t); void *erealloc(void *, size_t); @@ -32,6 +33,7 @@ char *estrdup(const char *); int easprintf(); int evasprintf(); void efree(); +void *ecalloc(); void *emalloc(); void *emalloc2(); void *erealloc();