malloc and calloc?

Match word(s).

If you have any questions or comments,
please visit us on the Forums.

FAQ > What's the difference between... > malloc and calloc?

This item was added on: 2003/03/13

Both malloc and calloc do the same thing with almost the same results, they allocate a block of n * sizeof ( T ) bytes of memory. The difference is in how the functions are called and how the memory block is initialized. malloc is called like so:

p = malloc ( n * sizeof ( T ) );

where the user programmer performs the operation to find the final block size. calloc takes two arguments and performs the operation itself:

p = calloc ( n, sizeof ( T ) );

malloc leaves the block of memory uninitialized, but calloc zero fills the memory. This does not mean that

p = calloc ( 1, sizeof ( int * ) );

will result in a pointer to int with a value of NULL. Zero filled memory does not mean that the memory is filled with the data type's equivalent of 0, so this zero fill cannot be relied on except with integral values such as int or char. Pointers and floating point may use a different representation for 0 than all bits zero.

Because of this zero fill, calloc can be slightly less efficient than malloc.

Credit: Prelude

Script provided by SmartCGIs