Tuesday, February 14, 2012

What is the difference between malloc and calloc ?


The basic difference between malloc() and calloc() is, in malloc() allocated memory is un-initialized, values in the allocated memory is undefined. Where as in calloc() allocated meory is initialized to zero. malloc will take only one argument size as input and retuns void pointer and calloc() need two arguments one is for size and second one is for size of the each allocated block and returns void pointer. For initialising the allocated memory, it needs the size of the each block, becaus of this calloc() needs second argument, it will specify the size of the each block.

void *malloc(size_t size)

void *calloc(size_t nmemb, size_t size)

char *ptr,*ptr1;
ptr = (char *)malloc(10*sizeof(char));
ptr1 = (char *)calloc(10,sizeof(char));

No comments:

Popular Posts