Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
calloc.c
Go to the documentation of this file.
1 #include <stdbool.h>
2 #include <stdlib.h>
3 #include <string.h>
4 
5 /*
6  * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
7  * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
8  */
9 #define MUL_NO_OVERFLOW (1UL << (sizeof(size_t) * 4))
10 
11 void* calloc(size_t num, size_t size)
12 {
13  /* num * size unsigned integer wrapping check */
14  if((num >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) && num > 0 && SIZE_MAX / num < size)
15  {
16  return NULL;
17  }
18 
19  size_t total_size = num * size;
20  void* ptr = malloc(total_size);
21 
22  if(ptr)
23  {
24  memset(ptr, 0, total_size);
25  }
26 
27  return ptr;
28 }
#define MUL_NO_OVERFLOW
Definition: calloc.c:9
#define NULL
Definition: stddef.h:15
void * memset(void *dest, int c, size_t n)
Copies the value c into each of the first n characters of the object pointed to by dest.
#define SIZE_MAX
Definition: stdint.h:279
void * malloc(size_t size)
Allocates size bytes of uninitialized storage.
void * calloc(size_t num, size_t size)
Allocates memory for an array of given number objects of size and initializes all bytes in the alloca...
Definition: calloc.c:11