C++ cstdlib calloc

The C++ <cstdlib> calloc function allocate memory in heap for an array of objects of specific size.The declaration of the function is given below.

void *calloc(size_t memsz , size_t size);

mem -The number of objects for whose memory is to be allocated .

size -The size of each object whose memory is to be allocated.

Return type
void* -A pointer to memory allocated.

Note here the pointer pointing to the memory is of ‘void’ type.

Some points to note:

i)If the memory allocation fails ‘caloc’ return NULL.So whenever you call this function you must test if the memory allocation was successful or failure.

ii)After the allocation the space is all initialized to 0.

iii)If the size-the first argument- pass is 0 the behavior is undefined.

iv)If this function is called do not forget to call the ‘free’ function to deallocate the storage,if you forget to do so there will be memory leakage.

Code example

void *mem=calloc( 4 , sizeof(char) ) ;

void *imem=calloc( 9 , sizeof(int) ) ;

free(imem); //do not forget
free(mem); //do not forget

‘mem’ points to memory which can hold 4 characters. ‘imem’ points to memory which can hols 9 integers.

Link : C free stdlib.h

A code example utilizing ‘calloc’ is given below.

#include <iostream>
#include <cstdlib>
#include <cstring>

using namespace std;

int main( )
char c[]=”New string” ;

void *cmem=calloc( strlen(c)+1 , sizeof(char) ) ; ///allocate memory that can hold ‘strlen(c)+1’ characters,the ‘strlen’ gives the number of characters in ‘c’

if( !cmem ) ///checks if ‘cmem’ is NULL
memcpy(cmem , c , strelen(c)+1 ); //copies the content of ‘c’ in ‘cmem’
  cout<< “Memory allocation failed” ;

//Accessing the content of cmem
cout<< *(static_cast<char*>(cmem)) << ” ”
<< *(static_cast<char*>(cmem+1)) << ” ”
<< *(static_cast<char*>(cmem+2)) ;


cin.get( );
return 0 ;


N e w

The ‘cmem’ memory is ‘void’ type,so casting the cmem to the appropriate type i.e. char type is necessary before accessing the value.

Link static_cast function

Related links

->C programming calloc