Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

What is the Difference between malloc and calloc?

What is the difference between doing:

ptr = (char
) malloc (MAXELEMS * sizeof(char *));


ptr = (char ) calloc (MAXELEMS, sizeof(char*));

When is it a good idea to use calloc over malloc or vice versa?

3 Answers

The difference between the above two is that for malloc only one argument is taken i.e., the number of bytes to be allocated whereas in calloc two arguments are taken. The first argument is for the number of blocks of memory to be allocated and the second argument is for the number of bytes to be allocated at each block of memory.
The use of calloc and malloc entirely depends on the requirement. For example, If there is a requirement to initialize the allocated memory by zero, then calloc is used over malloc. Whereas malloc is used over calloc as it is faster.
Only difference is the syntax
In malloc u find only one argument in the call i.e whole size
In calloc u find the number of elements as well as the memory allocatted for each element
malloc()* and *Calloc() both are used for dynamic memory allocations. The difference between malloc() and calloc() are :
malloc() takes a single argument that is the number of bytes where as calloc() takes two arguments, the number of blocks, and the size of the block.
malloc() does not initialize memory whereas calloc() initializes allocated memory to zero.
malloc() is faster than calloc().

Login / Signup to Answer the Question.