天天看點

calloc和malloc的差別,兼談new

都是動态配置設定記憶體。

Both the malloc() and the calloc() s 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 ); // 配置設定元素的個數和每個元素的大小

主要的不同是malloc不初始化配置設定的記憶體,calloc初始化已配置設定的記憶體為0。calloc等于malloc後在memset.

There are one major difference and one minor difference between the two. The major difference is that malloc() doesnt 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.

次要的不同是calloc傳回的是一個數組,而malloc傳回的是一個對象。

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 和 new 

至少有兩點不同。

一, new 傳回指定類型指針并且自動計算所需要大小比: 

int *p; 

p = new int; //傳回類型int* 類型(整數型指針)配置設定大小 sizeof(int); 

或: 

int* parr; 

parr = new int [100]; //傳回類型 int* 類型(整數型指針)配置設定大小 sizeof(int) * 100; 

而 malloc 則必須由我們計算要位元組數并且傳回強行轉換實際類型指針 

int* p; 

p = (int *) malloc (sizeof(int)); 

第一、malloc 函數傳回 void * 類型寫成:p = malloc (sizeof(int)); 則程式無法通過編譯報錯:能 void* 指派給 int * 類型變量所必須通過 (int *) 來強制轉換 

第二、函數實參 sizeof(int) 用于指明整型資料需要大小寫成:

int* p = (int *) malloc (1); 

代碼也能通過編譯事實上隻配置設定了1位元組大小記憶體空間當往裡頭存入整數會有3位元組無家歸而直接住進鄰居家造成結面記憶體原有資料内容全部被清空。

malloc 也能達到 new [] 效國申請出段連續記憶體,方法無非指定所需要記憶體大小 ,比如想配置設定100int類型空間: 

int* p = (int *) malloc ( sizeof(int) * 100 ); //配置設定放得下100整數記憶體空間 

二, 另外有點能直接看出差別:malloc 隻管配置設定記憶體,并不能對所得記憶體進行初始化。是以,在得到的一片新記憶體中,其值是随機的。

除了配置設定及釋放方法樣外通過malloc或new得指針其操作上保持緻。

當然,如果考慮到c++中類的構造概念,那差别就更大了。

繼續閱讀