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()

void *malloc(size_t size);

calloc()

void *calloc(size_t nelements, size_t bytes);

Example:

#include<stdio.h>
#include<stdlib.h>

int main() {
	char *str_malloc;

	char *str_calloc;

	/* Initial memory allocation */
	str_malloc = (char *) malloc(15); // it allocates 15 bytes of memory

	free(str_malloc); // free memory

	str_malloc = (char *) calloc(15, sizeof(char)); // it allocates 15 bytes of memory

	free(str_calloc); //free memory

	return (0);
}

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.



Related Contents to follow