Basically there are two difference between malloc() and calloc(). malloc() and the calloc() functions are used to allocate dynamic memory.

  • malloc malloc(memory required in bytes) takes a single argument while calloc(number of variables to allocate memory, size in bytes of a
    single variable) takes two arguments.
  • malloc() does not initialize the memory allocated, while calloc() initializes the allocated memory to ZERO.
  • malloc allocates memory in contiguous block if a contiguous block cannot be allocated then malloc would fail while memory allocated by calloc may/may not be contiguous.

memory allocated by malloc() or calloc() must be free by free( memory pointer).

Syntax

malloc()

calloc()

void *calloc(size_t nelements, size_t bytes);

Example:

differences between malloc and calloc

Interview Question on this topic:

  1. What functions can be used to allocate new memory in c?  Answer: malloc,calloc
  2. which function is used for deallocating memory allocated by malloc,calloc,realloc? Answer: by free() function
  3. where does memory resides or allocates when allocating memory with malloc,calloc,realloc? Answer: Heap
  4. which one is faster malloc or calloc? Answer: malloc

Explanation question 4:

malloc() is faster than calloc() as malloc() does not initialize memory while calloc() initialize memory to ZERO.