]> granicus.if.org Git - sudo/commitdiff
Add erealloc3(), a realloc() version of emalloc2().
authorTodd C. Miller <Todd.Miller@courtesan.com>
Wed, 12 Mar 2003 21:51:39 +0000 (21:51 +0000)
committerTodd C. Miller <Todd.Miller@courtesan.com>
Wed, 12 Mar 2003 21:51:39 +0000 (21:51 +0000)
alloc.c
sudo.h

diff --git a/alloc.c b/alloc.c
index d094915170e07597421e4d6eba24b3c820473cfa..dbd973d38af5f54033b28b5ec4877904178239fb 100644 (file)
--- 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 8201df7d204fb67216cd700199520e993a8e0d57..a562812582db81fdefa8db5875f9a9318d849d98 100644 (file)
--- 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));