C++動態記憶體分配

來源:互聯網
上載者:User

標籤:tor   get   ini   bsp   公司   view   cal   程式   south   

筆者介紹:薑雪偉,IT公司技術合伙人,IT進階講師,CSDN社區專家,特邀編輯,暢銷書作者,已出版書籍:《手把手教你架構3D遊戲引擎》電子工業出版社和《Unity3D實戰核心技術詳解》電子工業出版社等。

CSDN視頻網址:http://edu.csdn.net/lecturer/144

C / C ++中的動態記憶體分配是指程式員手動執行記憶體配置, 動態分配的記憶體配置給堆,非靜態和局部變數擷取在Stack上分配的記憶體。詳情查看上篇博文:C程式的記憶體布局。

什麼是應用程式?
動態分配的記憶體的一個用途是分配可變大小的記憶體,除了可變長度數組之外,編譯器是不可能分配記憶體的。
最重要的用途是為程式員提供靈活性,每當我們需要,並且我們不再需要了, 我們可以隨時分配和釋放記憶體,很多情況下,這種靈活性有所協助, 這種例子是連結清單,樹等。

與分配給正常變數的記憶體有什麼不同?
對於“int a”,“char str [10]”等常規變數,記憶體將自動分配和釋放。 對於動態分配的記憶體,如“int * p = new int [10]”,程式員有責任在不再需要時釋放記憶體。 如果程式員沒有釋放記憶體,它會導致記憶體流失(記憶體沒有釋放,直到程式終止)。

什麼是記憶體流失,如何避免?

當程式員在堆中建立記憶體並忘記刪除記憶體時,會發生記憶體流失,記憶體流失對於程式而言是特別嚴重的問題。以下是記憶體流失的代碼:

 

[cpp] view plain copy 
  1. /* Function with memory leak */  
  2. #include <stdlib.h>  
  3.    
  4. void f()  
  5. {  
  6.    int *ptr = (int *) malloc(sizeof(int));  
  7.    
  8.    /* Do some work */  
  9.    
  10.    return; /* Return without freeing ptr*/  
  11. }  

為了避免記憶體流失,分配給堆上的記憶體應該不再需要時被釋放。

 

 

[cpp] view plain copy 
  1. #include <stdlib.h>;  
  2.    
  3. void f()  
  4. {  
  5.    int *ptr = (int *) malloc(sizeof(int));  
  6.    
  7.    /* Do some work */  
  8.    
  9.    free(ptr);  
  10.    return;  
  11. }  

如何在C ++中分配/釋放記憶體?
C使用malloc()和calloc()函數在運行時動態分配記憶體,並使用free()函數釋放動態分配的記憶體。 C ++支援這些功能,並且還有兩個運算子new和delete來執行分配和釋放記憶體的任務。
這篇文章是關於new和delete的操作符。

 

new 操作符

new操作符表示堆上的記憶體配置請求。 如果有足夠的記憶體可用,new操作符初始化記憶體並將新分配和初始化的記憶體的地址返回給指標變數。

使用new操作符的文法:要分配任何資料類型的記憶體,文法為:

 

pointer-variable = new data-type;

 

這裡,指標變數是資料類型類型的指標,資料類型可以是任何內建資料類型,包括數組或任何使用者定義的資料類型,包括結構和類。

 

// Pointer initialized with NULL// Then request memory for the variableint *p = NULL; p = new int;               OR// Combine declaration of pointer // and their assignmentint *p = new int; 

初始化記憶體,我們可以使用new 初始化記憶體

 

 

pointer-variable = new data-type(value);Example:int *p = new int(25);float *q = new float(75.25);

 

分配記憶體塊:new運算子也用於分配資料類型的記憶體塊(數組)。

 

pointer-variable = new data-type[size];

 

其中size(一個變數)指定數組中的元素數。

 

int *p = new int[10]

 

動態地為類型int連續分配10個整數的記憶體,並返回指向序列的第一個元素的指標,分配給p(指標), p [0]是指第一個元素,p [1]是指第二個元素等等。

數組聲明用new操作符

聲明數組和使用new記憶體塊分配最重要的區別是,數組由編譯器釋放(如果數組是本地的,則在函數返回或完成時釋放)。 但是,動態分配的數組總是保留在那裡,直到它們被程式員或程式終止釋放。

如果運行時記憶體不足,怎麼辦?
如果堆中沒有足夠的記憶體可用於分配,則new請求通過拋出類型為std :: bad_alloc的異常來指示失敗,而new操作符返回一個指標。 因此,在使用該程式之前,檢查新的指標變數可能是一個好主意。

 

int *p = new int;if (!p){   cout << "Memory allocation failed\n";}

 

delete操作符

既然程式員有責任釋放動態分配的記憶體,所以使用C ++語言為程式員提供了delete操作符。

 

delete pointer-variable;

這裡,指標變數是指向由new建立的資料對象的指標。
例子:

 

 

  delete p;  delete q;

 

要釋放由指標變數指向的動態分配的數組,請使用以下形式的delete:

 

// Release block of memory // pointed by pointer-variabledelete[] pointer-variable;  Example:   // It will free the entire array   // pointed by p.   delete[] p;

 

完整的案例代碼如下所示:

 

[cpp] view plain copy 
  1. #include <iostream>  
  2. using namespace std;  
  3.    
  4. int main ()  
  5. {  
  6.     // Pointer initialization to null  
  7.     int* p = NULL;  
  8.    
  9.     // Request memory for the variable  
  10.     // using new operator  
  11.     p = new int;  
  12.     if (!p)  
  13.         cout << "allocation of memory failed\n";  
  14.     else  
  15.     {  
  16.         // Store value at allocated address  
  17.         *p = 29;  
  18.         cout << "Value of p: " << *p << endl;  
  19.     }  
  20.    
  21.     // Request block of memory  
  22.     // using new operator  
  23.     float *r = new float(75.25);  
  24.    
  25.     cout << "Value of r: " << *r << endl;  
  26.    
  27.     // Request block of memory of size n  
  28.     int n = 5;  
  29.     int *q = new int[n];  
  30.    
  31.     if (!p)  
  32.         cout << "allocation of memory failed\n";  
  33.     else  
  34.     {  
  35.         for (int i = 0; i < n; i++)  
  36.             q[i] = i+1;  
  37.    
  38.         cout << "Value store in block of memory: ";  
  39.         for (int i = 0; i < n; i++)  
  40.             cout << q[i] << " ";  
  41.     }  
  42.    
  43.     // freed the allocated memory  
  44.     delete p;  
  45.     delete r;  
  46.    
  47.     // freed the block of allocated memory  
  48.     delete[] q;  
  49.    
  50.     return 0;  
  51. }  

輸出結果:

 

 

Value of p: 29Value of r: 75.25Value store in block of memory: 1 2 3 4 5 

http://www.woaipu.com/shops/zuzhuan/61406
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117777
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117890
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=117994
http://nanning.xjwy.cn/f/bencandy.php?fid=43&id=118376



C++動態記憶體分配

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.