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

- 391,730
- 64
- 469
- 606

- 210
- 3
- 13
-
2On zeroes it the other doesn't. – cnicutar Aug 23 '12 at 08:51
-
2Take a look: [c difference between malloc and calloc](http://stackoverflow.com/questions/1538420/c-difference-between-malloc-and-calloc) – P.P Aug 23 '12 at 08:53
6 Answers
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.

- 5,320
- 1
- 25
- 43
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.

- 104,054
- 14
- 179
- 226
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.

- 9,158
- 7
- 41
- 63
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.

- 2,583
- 3
- 30
- 56
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.

- 549
- 7
- 10
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;
}

- 391,730
- 64
- 469
- 606