Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
calloc.c File Reference
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
Include dependency graph for calloc.c:

Go to the source code of this file.

Macros

#define MUL_NO_OVERFLOW   (1UL << (sizeof(size_t) * 4))
 

Functions

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 allocated storage to zero. More...
 

Macro Definition Documentation

◆ MUL_NO_OVERFLOW

#define MUL_NO_OVERFLOW   (1UL << (sizeof(size_t) * 4))

Definition at line 9 of file calloc.c.

Function Documentation

◆ calloc()

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 allocated storage to zero.

Allocates memory for an array of num objects of size size and initializes all bytes in the allocated storage to zero.

Parameters
numnumber of objects
sizesize of the array
Returns
(None)

Definition at line 11 of file calloc.c.

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.

References malloc(), memset(), MUL_NO_OVERFLOW, NULL, and SIZE_MAX.