C語言記憶體配置函數malloc——————【Badboy】,mallocbadboy
C語言中常用的記憶體配置函數有malloc、calloc和realloc等三個,其中,最常用的肯定是malloc,這裡簡單說一下這三者的區別和聯絡。
1、聲明
這三個函數都在stdlib.h庫檔案中,聲明如下:
void* realloc(void* ptr, unsigned newsize);
void* malloc(unsigned size);
void* calloc(size_t numElements, size_t sizeOfElement);
它們的功能大致類似,就是向作業系統請求記憶體配置,如果分配成功就返回分配到的記憶體空間的地址,如果沒有分配成功就返回NULL.
2、功能
malloc(size):在記憶體的動態儲存裝置區中分配一塊長度為"size"位元組的連續地區,返回該地區的首地址。
calloc(n,size):在記憶體的動態儲存裝置區中分配n塊長度為"size"位元組的連續地區,返回首地址。
realloc(*ptr,size):將ptr記憶體大小增大或縮小到size.
需要注意的是realloc將ptr記憶體增大或縮小到size,這時新的空間不一定是在原來ptr的空間基礎上,增加或減小長度來得到,而有可能(特別是在用realloc來增大ptr的記憶體空間的時候)會是在一個新的記憶體地區分配一個大空間,然後將原來ptr空間的內容拷貝到新記憶體空間的起始部分,然後將原來的空間釋放掉。因此,一般要將realloc的返回值用一個指標來接收,下面是一個說明realloc函數的例子。
#include
#include
int main()
{
//allocate space for 4 integers
int *ptr=(int *)malloc(4*sizeof(int));
if (!ptr)
{
printf("Allocation Falure!\n");
exit(0);
}
//print the allocated address
printf("The address get by malloc is : %p\n",ptr);
//store 10、9、8、7 in the allocated space
int i;
for (i=0;i<4;i++)
{
ptr[i]=10-i;
}
//enlarge the space for 100 integers
int *new_ptr=(int*)realloc(ptr,100*sizeof(int));
if (!new_ptr)
{
printf("Second Allocation For Large Space Falure!\n");
exit(0);
}
//print the allocated address
printf("The address get by realloc is : %p\n",new_ptr);
//print the 4 integers at the beginning
printf("4 integers at the beginning is:\n");
for (i=0;i<4;i++)
{
printf("%d\n",new_ptr[i]);
}
return 0;
}
運行結果如下:
從上面可以看出,在這個例子中新的空間並不是以原來的空間為基址分配的,而是重新分配了一個大的空間,然後將原來空間的內容拷貝到了新空間的開始部分。
3、三者的聯絡
calloc(n,size)就相當於malloc(n*size),而realloc(*ptr,size)中,如果ptr為NULL,那麼realloc(*ptr,size)就相當於malloc(size)。
..................................................................................................................................
C語言:要使用記憶體配置函數malloc,需要引入的標頭檔是malloch 還是stdlibh
你可以看一下C語言那本書後面的附錄。
使用動態記憶體分配函數時,實際上,許多編譯系統實現時,往往增加了一些其他函數。ANSI標準建議在“stdlib.h”標頭檔中包含有相關的資訊,但大多數C編譯系統要求用“mallco.h”而不是“stdlib.h”
C語言 malloc()函數 分配記憶體空間尺寸的問題
malloc是給指標變數分配記憶體空間的函數命令
正確使用:
分配的空間要能保證容下你想儲存的資料,不要和機器逗著玩(分配0空間,或少於自己實際需要的空間),如你上面的操作,表面上你程式運行沒有問題,可實際上你佔用了別人的地盤,只是當前你很幸運沒有使程式出現問題,但不保證一定不出問題!!
不再使用的指標,一定要free()來釋放空間!malloc 與free要配對使用,即:有malloc必要有free