The GNU C Library - Allocating Cleared Space

Node: Allocating Cleared Space Next: Efficiency and Malloc Prev: Changing Block Size Up: Unconstrained Allocation

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)
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)
	{
	  size_t size = count * eltsize;
	  void *value = malloc (size);
	  if (value != 0)
	    memset (value, 0, size);
	  return value;
	}

We rarely use calloc today, because it is equivalent to such a simple combination of other features that are more often used. It is a historical holdover that is not quite obsolete.


Next: Efficiency and Malloc Up: Unconstrained Allocation