Sunday, 14 August 2011

What is the difference between "calloc(...)" and "malloc(...)"?

1. calloc(...) allocates a block of memory for an array of elements of a certain size. By default the block is initialized to 0. The total number of memory allocated will be (number_of_elements * size).


malloc(...) takes in only a single argument which is the memory required in bytes. malloc(...) allocated bytes of memory and not blocks of memory like calloc(...).


calloc(...) allocates an array in memory with elements initialized to 0 and returns a pointer to the allocated space. calloc(...) calls malloc(...) in order to use the C++ _set_new_mode function to set the new handler mode.

both of the functions we need not do a explicit typecasting. on success they return address of the allocated area n on failure they return NULL.

Another difference is that calloc takes two arguments while malloc takes only one argument.
malloc: eg:


int *p;
p=(int*)malloc(sizeof(int)*5)

calloc: eg:
p=(int*)calloc(5,sizeof(int)*5)



Calloc: Memory Cannot be modified using realloc() function

Malloc:
Memory Can be modified using realloc() function


one difference is that calloc not contain garbage value where malloc allocated memory contain garbage value .



No comments:

Post a Comment