爲什麼存在動態記憶體分配?
開闢空間的方式有兩個特點:
- 空間開闢大小是固定的。
- 陣列在申明的時候,必須指定陣列的長度,它所需要的記憶體在編譯時分配。
但是對於空間的需求,不僅僅是上述的情況。有時候我們需要的空間大小在程式執行的時候才能 纔能知道,那陣列的編譯時開闢空間的方式就不能滿足了。 這時候就只能試試動態存開闢了。
malloc和free
void* malloc(size_t size);
C語言提供了另外一個函數free,專門是用來做動態記憶體的釋放和回收的,函數原型如下:
void free (void* ptr);
malloc和free都宣告在 stdlib.h 標頭檔案中。
calloc
void* calloc(size_t num, size_t size);
realloc
void* realloc(void* ptr, size_t size);
在c++中,有參照了新的動態記憶體開闢函數new,delete
new
void Test()
{
// 動態申請一個int型別的空間
int* ptr4 = new int;
// 動態申請一個int型別的空間並初始化爲10
int* ptr5 = new int(10);
// 動態申請10個int型別的空間
int* ptr6 = new int[3];
delete ptr4;
delete ptr5;
delete[] ptr6;
}
申請和釋放單個元素的空間,使用new和delete操作符,申請和釋放連續的空間,使用new[]和delete[]
new和delete是使用者進行動態記憶體申請和釋放的操作符,operator new 和operator delete是系統提供的全域性函數,new在底層呼叫operator new全域性函數來申請空間,delete在底層通過operator delete全域性函數來釋放空間
operator new: 該函數實際通過malloc來申請空間,當malloc申請空間成功時直接返回;申請空間失敗,嘗試執行空 間不足應對措施,如果改應對措施使用者設定了,則繼續申請,否則拋異常。
operator delete: 該函數最終是通過free來釋放空間的
new的原理
delete的原理
在空間上執行析**構函數,完成物件中資源的清理工作
呼叫operator delete函數釋放物件的空間
new T[N]的原理
delete[]的原理
malloc/free和new/delete的共同點是:都是從堆上申請空間,並且需要使用者手動釋放。不同的地方是:
關於記憶體分配的試題
int globalVar = 1;
static int staticGlobalVar = 1;
void Test()
{
static int staticVar = 1;
int localVar = 1;
int num1[10] = {1, 2, 3, 4};
char char2[] = "abcd";
char* pChar3 = "abcd";
int* ptr1 = (int*)malloc(sizeof (int)*4);
int* ptr2 = (int*)calloc(4, sizeof(int));
int* ptr3 = (int*)realloc(ptr2, sizeof(int)*4);
free (ptr1);
free (ptr3);
}
1. 選擇題:
選項: A.棧 B.堆 C.數據段 D.程式碼段
globalVar在哪裏?____ staticGlobalVar在哪裏?____
staticVar在哪裏?____ localVar在哪裏?____
num1 在哪裏?____
char2在哪裏?____ *char2在哪裏?___
pChar3在哪裏?____ *pChar3在哪裏?____
ptr1在哪裏?____ *ptr1在哪裏?____
2. 填空題:
sizeof(num1) = ____;
//C語言中動態記憶體管理方式
malloc/calloc/realloc和free
sizeof(char2) = ____; strlen(char2) = ____;
sizeof(pChar3) = ____; strlen(pChar3) = ____;
sizeof(ptr1) = ____;