calloc -- Reserve and Initialize Storage

Format

#include <stdlib.h>
/* also in <malloc.h>   */
void *calloc(size_t num, size_t size);

Language Level: ANSI, POSIX, XPG4
calloc reserves storage space for an array of num elements, each of length size bytes. calloc then gives all the bits of each element an initial value of 0.

Heap-specific and tiled versions of this function (_ucalloc and _tcalloc) are also available on OS/2.

On Windows, a heap-specific version of this function (_ucalloc) is also available.

In both OS/2 and Windows, calloc always allocates memory from the default heap. You can also use the debug version of calloc, _debug_calloc, to debug memory problems.

Return Value
calloc returns a pointer to the reserved space. The storage space to which the return value points is suitably aligned for storage of any type of object. To get a pointer to a type, use a type cast on the return value. The return value is NULL if there is not enough storage, or if num or size is 0.

Example
This example prompts for the number of array entries required and then reserves enough space in storage for the entries. If calloc is successful, the example prints out each entry; otherwise, it prints out an error.

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
  long * array;                             /* start of the array */
  long * index;                             /* index variable     */
  int i;                                    /* index variable     */
  int num;                                  /* number of entries of the array */
  printf( "Enter the size of the array\n" );
  scanf( "%i", &num );
                                            /* allocate num entries */
  if ( (index = array = (long *) calloc( num, sizeof( long ))) != NULL )
  {
    for ( i = 0; i < num; ++i )             /* put values in array    */
       *index++ = i;                        /* using pointer notation */
    for ( i = 0; i < num; ++i )             /* print the array out    */
      printf( "array[ %i ] = %i\n", i, array[i] );
  }
  else
  { /* out of storage */
    perror( "Out of storage" );
    abort();
  }
   /*******************************************************************
      The output should be similar to :
      Enter the size of the array
      3
      array[ 0 ] = 0
      array[ 1 ] = 1
      array[ 2 ] = 2
   *******************************************************************/
}


Memory Management


_alloca -- Temporarily Reserve Storage Block
_debug_calloc -- Allocate and Initialize Memory
_debug_tcalloc -- Reserve and Initialize Tiled Memory
_debug_ucalloc -- Reserve and Initialize Memory from User Heap
free -- Release Storage Blocks
malloc -- Reserve Storage Block
realloc -- Change Reserved Storage Block
_tcalloc -- Reserve Tiled Storage Block
_ucalloc -- Reserve and Initialize Memory from User Heap
<malloc.h>
<stdlib.h>