发新话题
打印

[转载]malloc和calloc的区别

[转载]malloc和calloc的区别

文章作者:Prelude

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.
qq310926是我唯一用号,除此之外有其他号码号自称邪八冰血封情,则非本人。

TOP

发新话题