Print this page
4922 all calloc() implementations should check for overflow

@@ -25,20 +25,19 @@
  */
 
 /*      Copyright (c) 1988 AT&T */
 /*        All Rights Reserved   */
 
-#pragma ident   "%Z%%M% %I%     %E% SMI"
-
 #include <sys/types.h>
 
 #ifndef debug
 #define NDEBUG
 #endif
 
 #include <stdlib.h>
 #include <string.h>
+#include <errno.h>
 #include "assert.h"
 #include "malloc.h"
 #include "mallint.h"
 #include <thread.h>
 #include <pthread.h>

@@ -843,16 +842,28 @@
 
 void *
 calloc(size_t num, size_t size)
 {
         char *mp;
+        size_t total;
+
+        if (num == 0 || size == 0) {
+                total = 0;
+        } else {
+                total = num * size;
+
+                /* check for overflow */
+                if ((total / num) != size) {
+                        errno = ENOMEM;
+                        return (NULL);
+                }
+        }
 
-        num *= size;
-        mp = malloc(num);
+        mp = malloc(total);
         if (mp == NULL)
                 return (NULL);
-        (void) memset(mp, 0, num);
+        (void) memset(mp, 0, total);
         return (mp);
 }
 
 
 /*