Friday, July 31, 2009

Explain the diffrence between of malloc & calloc, in c programming?

Explain the diffrence between of malloc %26amp; calloc, in c programming

Explain the diffrence between of malloc %26amp; calloc, in c programming?
void *malloc(size_t size);





The function allocates an object of size_t size (size_t = int, char, float...etc), and returns the address of the object if successful; otherwise, it returns a null pointer. The values stored in the object are indeterminate. You can safely convert the return value to an object pointer of any type whose size is not greater than size.





void *calloc(size_t nelem, size_t size);





The function allocates an array object containing nelem (number of elements) each of size_t size, stores zeros in all bytes of the array, and returns the address of the first element of the array if successful; otherwise, it returns a null pointer. You can safely convert the return value to an object pointer of any type whose size in bytes is not greater than size.
Reply:Malloc is for 1 dimensional chunks of memory





Calloc is for 2 dimensional chunks of memory
Reply:calloc is for allocating an array of n elements, each of size (in


bytes) m. The memory returned will have been completely


initiailzed to zero (0).





malloc is more primitive and simply returns a big block of


uninitialized memory of the size (in bytes) that is requested.





These bits of code are equivilant:





1,


char *alfs = (char *) malloc(50);


if (alfs)


memset(alfs, 0, 50);





2.


char *alfs = (char *) calloc(50, 1);


No comments:

Post a Comment