Monday, May 24, 2010

Wat is diff b/w malloc &calloc functioin?

it is a c language question ask in a interview

Wat is diff b/w malloc %26amp;calloc functioin?
malloc is used to allocate a certain number of bytes of memory. It only takes one parameter, the number of bytes. Usually, malloc doesn't initialise the allocated memory to zero, the contents of the memory will be undefined.





calloc is used to allocate a certain number of blocks of memory, with each block being of a certain size. It takes two parameters, the first one is the number of blocks and the second one is the size of each block in bytes. Unlike malloc, calloc does initialize all the blocks of memory to zero bytes.
Reply:malloc and calloc r both used to allocate memory dynamically


syntax of malloc is:(cast-type *)malloc(sizeof(bytesize);


casttype is the return type and byte size specifies the number of bytes to allocate


whereas syntax of calloc is


(cast-type *)calloc(n,bytesize);


n here specifies the number of blocks to be allocated


i.e, n blocks of bytesize each is allocated


and also calloc intializes the blocks to zero value.
Reply:http://www.careercup.com/question/?q=4f9...
Reply:1. they have different names..


2. they have different prototype(that is u call them differently).


void * calloc(size_t n, size_t size)


void * malloc(size_t bytes)





But both do the same thing.. they return the pointer to the newly allocated memory block(given that the block was allocated)





note:: size_t is an unsigned integer.... (remember typedef ???)


No comments:

Post a Comment