In C programming <stdlib.h> 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.
void* -A pointer to memory allocated.
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.
char *mem=(char*)calloc( 4 , sizeof(char) ) ; //work fine
void *imem=calloc( 9 , sizeof(int) ) ;
free(imem); //do not forget
free(mem); //do not forget
In the first line the pointer returned by ‘calloc’ is casted to ‘int*’ to type so assigning the returned pointer to ‘mem’ pointer is totally fine.In the second line casting is not needed because ‘imem’ is ‘void*’ type.
Link : C free stdlib.h
A more exhaustive code example using ‘calloc’ is given below.
int main( )
int *imem = (int*)calloc(4, sizeof(int));
void *cmem = calloc(5 , strlen(c)+1 );
memcpy(imem, i, sizeof(int) * 4); //copying the content of ‘i’ array to memory pointed by imem
memcpy(cmem, c, strlen(c) + 1); //copying the content of ‘c’ string to memory pointed by cmem
printf(“%i %i “, imem, imem ); //accessing the content stored in ‘imem’ memory
printf(“\n%c %c “, *((char*)cmem), *(((char*)cmem)+1) ); //accessing the content stored in ‘cmem’ memory
Output in VS,
i)’imem’ is ‘int*’ so we can directly access the content of the memory pointed by imem using the array syntax(the subscript ).
ii)Since ‘cmem’ is ‘void*’ type we have to cast it to ‘char*’ type first before accessing the content of the memory.And this done by adding the (char*) before the ‘cmem’ pointer.
Link : C what is casting??