3

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

unwind
  • 391,730
  • 64
  • 469
  • 606
Kusum Adhikari
  • 210
  • 3
  • 13

6 Answers6

5

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.

Abhineet
  • 5,320
  • 1
  • 25
  • 43
0

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.

justin
  • 104,054
  • 14
  • 179
  • 226
0

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;
for(i=0; i< 100; i++)
    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.

Jeyaram
  • 9,158
  • 7
  • 41
  • 63
0

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.

Julien Fouilhé
  • 2,583
  • 3
  • 30
  • 56
0

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.

Anup H
  • 549
  • 7
  • 10
0

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;
}
unwind
  • 391,730
  • 64
  • 469
  • 606