Difference between malloc and calloc in C

Malloc and Calloc are functions provided to allocate memory at run time.Both of these functions return pointer to first block of  allocated memory in success and return null in case of failure.
Though their purpose is same, there are few differences between them.

1. No. of Arguments: 
Both these functions vary in number of arguments they accept.

void *malloc(size_t size);

void *calloc(size_t n, size_t size);

Malloc takes only one argument that describes size of block to be allocated in memory.

e.g. oPointer = (int *)malloc(sizeof(int) * 2); will allocate size of 4 bytes(size of int is 2 bytes).
Whereas, Calloc takes two arguments number of blocks and size of each block.
e.g. oPointer = (int *)calloc(2 ,sizeof(int)); will allocate size of 4 bytes(size of int is 2 bytes).

2. Default Initialization: 
Malloc does not initialize the memory allocated whereas calloc initializes the allocated memory to default (e.g. Zero).

3. Calculation of memory reuired:
Malloc function does not calculate total memory to be allocated, the argument itself describes the total memory whereas, calloc accepts two argument and internally calculates their product to find total memory to be allocated.


Post a Comment