Take the 2-minute tour ×

Can anyone explain what is the difference between using malloc() and calloc() for dynamic memory allocation in C?

share|improve this question
On zeroes it the other doesn't. –  cnicutar Aug 23 '12 at 8:51
Take a look: c difference between malloc and calloc –  Blue Moon Aug 23 '12 at 8:53

6 Answers 6

up vote 4 down vote accepted

Try doing this: Allocate some memory using malloc like

char* pszKuchBhi ;
pszKuchBhi = malloc(10) ;
printf( "%s\n", pszKuchBhi ) ;  
// Will give some junk values as the memory allocated is not initialized and 
// was storing some garbage values

Now do the same while replacing malloc with calloc. See the difference.

char* pszKuchBhi ;
pszKuchBhi = calloc( 10, 1 ) ;
printf( "%s\n", pszKuchBhi ) ; 
//Will print nothing as the memory is initialized to 0

The memory assigned by calloc is initialized to 0. Its good for beginners to initialize the memory but performance-wise calloc is slow as it has to allocate and then initialize. For better clarification, you can always google the same question but better to experience it to have a look inside. You can also keep a watch on your memory to see it for yourself.

share|improve this answer

malloc returns an allocation with a fixed number of bytes. this memory is not cleared (garbage values).

calloc returns an allocation for a fixed number of objects of a specific memory. this memory is zeroed.

share|improve this answer

If you want to allocate 100 int. You'll have to do like this :

int *var;

var = malloc(100 * sizeof(int));
// OR
var = calloc(100, sizeof(int));

Because malloc takes a number of bytes in parameter while calloc takes a number and an element, it's doing the calc itself, and fill all the memory allocated with zeroes.

share|improve this answer

Allocating 100 bytes of memory which is initialized to 0.

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

If we use malloc(), then

char *ptr = malloc(100);
int i = 0;
    ptr[i] = 0;

Immediately after allocating memory, If initialization happens better we can go for malloc(). It is unnecessary to initialize to 0, then initialize with data.

share|improve this answer

When you allocate the memory using malloc, the memory is simply allocated with garbage values and when you allocate the memory using calloc, the memory is allocated and the each memory location is filled with 0.

share|improve this answer

One is a primitive (malloc()), the other is more of a convenience function (calloc()). In essense, you can think of calloc() being implemented like so:

void * my_calloc(size_t num_elems, size_t elem_size)
  const size_t bytes = num_elems * elem_size;
  void *p;

  if((p = malloc(bytes)) != NULL)
    memset(p, 0, bytes);
  return p;
share|improve this answer

Your Answer


