malloc函數

轉載自:http://blog.csdn.net/xw13106209/article/details/4962479
程序員


1、原型:extern void *malloc(unsigned int num_bytes);數組

頭文件:#include <malloc.h> 或 #include <alloc.h> (注意:alloc.h 與 malloc.h 的內容是徹底一致的。)函數

功能:分配長度爲num_bytes字節的內存塊ui

說明:若是分配成功則返回指向被分配內存的指針,不然返回空指針NULL。spa

當內存再也不使用時,應使用free()函數將內存塊釋放。操作系統

 

舉例:
.net

[c-sharp] view plain copy
  1. #include<stdio.h>  
  2. #include<malloc.h>  
  3. int main()  
  4. {  
  5.     char *p;  
  6.    
  7.     p=(char *)malloc(100);  
  8.     if(p)  
  9.         printf("Memory Allocated at: %x/n",p);  
  10.     else  
  11.         printf("Not Enough Memory!/n");  
  12.     free(p);  
  13.     return 0;  
  14. }  

 

 

2、函數聲明(函數原型): 指針

  void *malloc(int size); blog

  說明:malloc 向系統申請分配指定size個字節的內存空間。返回類型是 void* 類型。void* 表示未肯定類型的指針。C,C++規定,void* 類型能夠強制轉換爲任何其它類型的指針。這個在MSDN上能夠找到相關的解釋,具體內容以下:ip

     

malloc returns a void pointer to the allocated space, or NULL if there is insufficient memory available. To return a pointer to a type other than void, use a type cast on the return value. The storage space pointed to by the return value is guaranteed to be suitably aligned for storage of any type of object. If size is 0, malloc allocates a zero-length item in the heap and returns a valid pointer to that item. Always check the return from malloc, even if the amount of memory requested is small.

3、malloc與new的不一樣點

  從函數聲明上能夠看出。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));

 

  第1、malloc 函數返回的是 void * 類型,若是你寫成:p = malloc (sizeof(int)); 則程序沒法經過編譯,報錯:「不能將 void* 賦值給 int * 類型變量」。因此必須經過 (int *) 來將強制轉換。

  第2、函數的實參爲 sizeof(int) ,用於指明一個整型數據須要的大小。若是你寫成:

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

  代碼也能經過編譯,但事實上只分配了1個字節大小的內存空間,當你往裏頭存入一個整數,就會有3個字節無家可歸,而直接「住進鄰居家」!形成的結果是後面的內存中原有數據內容所有被清空。

  malloc 也能夠達到 new [] 的效果,申請出一段連續的內存,方法無非是指定你所須要內存大小。

  好比想分配100個int類型的空間:

  int* p = (int *) malloc ( sizeof(int) * 100 ); //分配能夠放得下100個整數的內存空間。

  另外有一點不能直接看出的區別是,malloc 只管分配內存,並不能對所得的內存進行初始化,因此獲得的一片新內存中,其值將是隨機的。

  除了分配及最後釋放的方法不同之外,經過malloc或new獲得指針,在其它操做上保持一致。

 

 總結:

malloc()函數其實就在內存中找一片指定大小的空間,而後將這個空間的首地址範圍給一個指針變量,這裏的指針變量能夠是一個單獨的指針,也能夠是一個數組的首地址,這要看malloc()函數中參數size的具體內容。咱們這裏malloc分配的內存空間在邏輯上連續的,而在物理上能夠連續也能夠不連續。對於咱們程序員來講,咱們關注的是邏輯上的連續,由於操做系統會幫咱們安排內存分配,因此咱們使用起來就能夠當作是連續的。

相關文章
相關標籤/搜索