From 838ec0a2ca94bbff019207851166574547a1b334 Mon Sep 17 00:00:00 2001 From: "Todd C. Miller" Date: Wed, 12 Mar 2003 21:51:39 +0000 Subject: [PATCH] Add erealloc3(), a realloc() version of emalloc2(). --- alloc.c | 35 ++++++++++++++++++++++++++++++++++- sudo.h | 1 + 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/alloc.c b/alloc.c index d09491517..dbd973d38 100644 --- a/alloc.c +++ b/alloc.c @@ -120,7 +120,8 @@ emalloc2(nmemb, size) Argv[0]); exit(1); } - if ((ptr = (VOID *) malloc(nmemb * size)) == NULL) { + size *= nmemb; + if ((ptr = (VOID *) malloc(size)) == NULL) { (void) fprintf(stderr, "%s: cannot allocate memory!\n", Argv[0]); exit(1); } @@ -151,6 +152,38 @@ erealloc(ptr, size) return(ptr); } +/* + * erealloc3() realloc(3)s nmemb * size bytes and exits with an error + * if overflow would occur or if the system malloc(3)/realloc(3) fails. + * You can call erealloc() with a NULL pointer even if the system realloc(3) + * does not support this. + */ +VOID * +erealloc3(ptr, nmemb, size) + VOID *ptr; + size_t nmemb; + size_t size; +{ + + if (nmemb == 0 || size == 0) { + (void) fprintf(stderr, "%s: internal error, tried to realloc(0)\n", + Argv[0]); + exit(1); + } + if (nmemb >= SIZE_MAX / size) { + (void) fprintf(stderr, "%s: internal error, erealloc3() overflow\n", + Argv[0]); + exit(1); + } + size *= nmemb; + ptr = ptr ? (VOID *) realloc(ptr, size) : (VOID *) malloc(size); + if (ptr == NULL) { + (void) fprintf(stderr, "%s: cannot allocate memory!\n", Argv[0]); + exit(1); + } + return(ptr); +} + /* * estrdup() is like strdup(3) except that it exits with an error if * malloc(3) fails. NOTE: unlike strdup(3), estrdup(NULL) is legal. diff --git a/sudo.h b/sudo.h index 8201df7d2..a56281258 100644 --- a/sudo.h +++ b/sudo.h @@ -214,6 +214,7 @@ void pass_warn __P((FILE *)); VOID *emalloc __P((size_t)); VOID *emalloc2 __P((size_t, size_t)); VOID *erealloc __P((VOID *, size_t)); +VOID *erealloc3 __P((VOID *, size_t, size_t)); char *estrdup __P((const char *)); int easprintf __P((char **, const char *, ...)); int evasprintf __P((char **, const char *, va_list)); -- 2.40.0