3.2.3.6 Allocating Cleared Space

The function calloc allocates memory and clears it to zero. It is declared in stdlib.h.

Function: void * calloc (size_t count, size_t eltsize)

Preliminary: | MT-Safe | AS-Unsafe lock | AC-Unsafe lock fd mem | See POSIX Safety Concepts.

This function allocates a zeroed vector. It acts like reallocarray (NULL, count, eltsize) except that the vector’s contents are cleared to zero before calloc returns.

You could define calloc as follows:

void *
calloc (size_t count, size_t eltsize)
{
  void *p = reallocarray (0, count, eltsize);
  if (p != NULL)
    memset (p, 0, count * eltsize);
  return p;
}

But in general, it is not guaranteed that calloc calls reallocarray and memset internally. For example, if the calloc implementation knows for other reasons that the new memory block is zero, it need not zero out the block again with memset. Also, if an application provides its own reallocarray outside the C library, calloc might not use that redefinition. See Replacing malloc.