Print this page
XXXX all calloc() implementations should check overflow

@@ -22,28 +22,40 @@
 /*
  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
  * Use is subject to license terms.
  */
 
-#pragma ident   "%Z%%M% %I%     %E% SMI"
-
 #include <stdlib.h>
 #include <string.h>
+#include <errno.h>
+
 /*
  * calloc - allocate and clear memory block
  */
 
 void *
 calloc(size_t num, size_t size)
 {
         void *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);
 }
 
 /*ARGSUSED*/
 void