summaryrefslogtreecommitdiff
path: root/lib/libc/stdlib/calloc.c
blob: 89e16f804bd736e46e450d9c81a2caf25d72cfb6 (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
26
27
#include "stddef.h" // for NULL

#include <errno.h>  // for errno, EINVAL, ENOMEM
#include <stdlib.h> // for calloc, malloc
#include <string.h> // for size_t, memset

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;
}