🌈個人主頁:羽晨同學?
💫個人格言:“成為自己未來的主人~”??
C/C++內存分布
在這篇文章開始之前,我們先以一道題目來進行引入:
int glovalvar = 1;
static int staticGlovalvar = 1;
void Test()
{static int staticvar = 1;int localvar = 1;int num1[10] = { 1,2,3,4 };char char2[] = "abcd";const 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) = ____;
sizeof(char2) = ____; strlen(char2) = ____;
sizeof(pChar3) = ____; strlen(pChar3) = ____;
sizeof(ptr1) = ____;
?
3 sizeof 和 strlen 區別?
大家可以先想想,這些問題的答案是什么?
說明:
- 棧又叫堆棧-非靜態局部變量/返回值等等,棧是向下增長的。
- 內存映射段,是高效的I/O映射方式,用于裝載一個共享的動態內存庫,用戶可使用系統接口創建共享內存,做進程間通信。
- 堆用于程序運行時動態內存分配,堆是向上增長的。
- 數據段-存儲全局數據和靜態數據
- 代碼段-可執行的代碼/只讀變量。
C++內存管理方式
C語言內存管理方式在C++中可以繼續使用,但有些地方就無能為力,而且使用起來比較麻煩,因此C++又提出了自己的內存管理方式,通過new和delete操作符進行動態內存管理。
new和delete的操作內置類型
int main()
{//內置類型int* p1 = new int;int* p2 = new int[10];return 0;
}
內置類型默認不初始化,但是,也可以進行初始化。
int main()
{內置類型//int* p1 = new int;//int* p2 = new int[10];int* p1 = new int(10);int* p2 = new int[10] {1, 2, 3, 4};//其余都是0delete p1;delete [] p2;return 0;
}
申請和釋放單個元素的空間,使用new和delete操作符,申請和釋放連續的空間,使用new[]和delete[],注意:匹配起來使用。
?為什么要匹配起來使用呢?我們后面再說。
我們可以看出來,當處理內置類型的時候,malloc和new是幾乎沒有任何區別的。
new和delete操作自定義類型
class A
{
public:A(int a = 0):_a(a){cout << "A(int a = 0)" << endl;}A(int a1, int a2){cout << " A(int a1, int a2)" << endl;}A(const A& aa):_a(aa._a){cout << " A(const A& aa)" << endl;}A& operator=(const A& aa){cout << "A& operator=(const A& aa)" << endl;if (this != &aa){_a = aa._a;}return *this;}~A(){cout << "~A()" << endl;}
private:int _a;
};
int main()
{//自定義類型,new才能調用構造初始化,malloc不能A* p1 = (A*)malloc(sizeof(A));free(p1);A* p2 = new A;A* p3 = new A(2);delete p2;delete p3;return 0;
}
我們可以從這段代碼當中得出一個很重要的點,那就是malloc不能調用構造初始化,但是new可以
//A* p4 = new A[10];//A aa1(1);//A aa2(2);//A aa3(3);//A* p4 = new A[10]{ aa1,aa2,aa3 };A* p4 = new A[10]{ 1,2,3,4,5,{6,7} };delete[] p4;
?
?
?