summaryrefslogtreecommitdiff
path: root/lib/libc/stdlib/calloc.c
blob: 408eef5ef0724e057e51acab92a4228f62ed344b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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;
}