C語言記憶體配置函數malloc——————【Badboy】

來源:互聯網
上載者:User

標籤:malloc   art   src   ted   沒有   add   com   printf   csdn   

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——————【Badboy】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.