Next: , Previous: , Up: Unconstrained Allocation   [Contents][Index]


3.2.3.5 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 block long enough to contain a vector of count elements, each of size eltsize. Its contents are cleared to zero before calloc returns.

You could define calloc as follows:

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

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.