1. 程式人生 > >malloc和calloc區別(c)

malloc和calloc區別(c)

 網上找到的英文解釋如下:
Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other.

Both the malloc() and the calloc() functions are used to allocate dynamic memory. Each operates slightly different from the other. malloc() takes a size and returns a pointer to a chunk of memory at least that big:
void *malloc( size_t size );
calloc() takes a number of elements, and the size of each, and returns a pointer to a chunk of memory
at least big enough to hold them all:
void *calloc( size_t numElements, size_t sizeOfElement );
There are one major difference and one minor difference between the two functions. The major difference is that malloc() doesn't initialize the allocated memory. The first time malloc() gives you a particular chunk of memory, the memory might be full of zeros. If memory has been allocated, freed, and reallocated, it probably has whatever junk was left in it. That means, unfortunately, that a program might run in simple cases (when memory is never reallocated) but break when used harder (and when memory is reused). calloc() fills the allocated memory with all zero bits. That means that anything there you are going to use as a char or an int of any length, signed or unsigned, is guaranteed to be zero. Anything you are going to use as a pointer is set to all zero bits.
That is usually a null pointer, but it is not guaranteed.Anything you are going to use as a float or double is set to all zero bits; that is a floating-point zero on some types of machines, but not on all.
The minor difference between the two is that calloc() returns an array of objects; malloc() returns one object. Some people use calloc() to make clear that they want an array.

下面是網上的中文說明

malloc()函式更好還是用calloc()函式更好函式malloc()calloc()都可以用來動態分配記憶體空間,但兩者稍有區別。

malloc()
函式有一個引數,即要分配的記憶體空間的大小:

void*malloc(size_tsize);

calloc()函式有兩個引數,分別為元素的數目和每個元素的大小,這兩個引數的乘積就是要分配的記憶體空間的大小。

void*
calloc(size_tnumElements,size_tsizeOfElement);

如果呼叫成功,函式malloc()和函式calloc()都將返回所分配的記憶體空間的首地址。函式malloc()和函式calloc()
的主要區別是前者不能初始化所分配的記憶體空間,而後者能。如果由malloc()函式分配的記憶體空間原來沒有被使用過,則其中的每一位可能都是0;反之, 如果這部分記憶體曾經被分配過,則其中可能遺留有各種各樣的資料。也就是說,使用malloc()函式的程式開始時(記憶體空間還沒有被重新分配)能正常進 ,但經過一段時間(記憶體空間還已經被重新分配)可能會出現問題。函式calloc() 會將所分配的記憶體空間中的每一位都初始化為零,也就是說,如果你是為字元型別或整數型別的元素分配記憶體,那麼這些元素將保證會被初始化為0;如果你是為指 針型別的元素分配記憶體,那麼這些元素通常會被初始化為空指標;如果你為實型資料分配記憶體
,則這些元素會被初始化為浮點型的零。