summaryrefslogtreecommitdiff
path: root/lib/libc/stdlib/calloc.c
diff options
context:
space:
mode:
Diffstat (limited to 'lib/libc/stdlib/calloc.c')
-rw-r--r--lib/libc/stdlib/calloc.c25
1 files changed, 25 insertions, 0 deletions
diff --git a/lib/libc/stdlib/calloc.c b/lib/libc/stdlib/calloc.c
new file mode 100644
index 00000000..408eef5e
--- /dev/null
+++ b/lib/libc/stdlib/calloc.c
@@ -0,0 +1,25 @@
+#include <errno.h>
+#include <string.h>
+#include <stdlib.h>
+
+void *calloc(size_t nelem, size_t elsize)
+{
+ void *ptr;
+ size_t total;
+
+ if (nelem == 0 || elsize == 0) {
+ errno = EINVAL;
+ return NULL;
+ }
+
+ if (__builtin_mul_overflow(nelem, elsize, &total)) {
+ errno = ENOMEM;
+ return NULL;
+ }
+
+ if ((ptr = malloc(total)) != NULL) {
+ memset(ptr, 0, total);
+ }
+
+ return ptr;
+}