目錄
引入
分析
說明
C語言中動態內存管理方式
C++內存管理方式
new/delete操作內置類型
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";
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 區別?

分析
全局變量與static變量均在靜態區(static變量在第一次載入時初始化)
字符串均在常量區,如果是采用數組方式,那么就是從常量區將字符串拷貝到棧區中,因此對字符串數組存儲在棧中,而下面的字符串指針指向字符串所存儲的位置,字符串本身存儲在常量區中
注意:const char* ptr="abcd",*ptr在常量區,因為*ptr無法被修改,因此會直接將常量區的位置傳遞給指針
各種變量,包括int char 指針類型變量都存儲在棧中
sizeof如果是整個數組則返回數組大小,如果是其他類型變量則返回變量大小
strlen返回的是字符串長度從第一個元素到'\0'之前的元素個數
說明
1. 棧 又叫堆棧 -- 非靜態局部變量 / 函數參數 / 返回值等等,棧是向下增長的。
2. 內存映射段 是高效的 I/O 映射方式,用于裝載一個共享的動態內存庫。用戶可使用系統接口創建共享共 享內存,做進程間通信。(linux部分會講)
3. 堆 用于程序運行時動態內存分配,堆是可以上增長的。
4. 數據段 -- 存儲全局數據和靜態數據。
5. 代碼段 -- 可執行的代碼 / 只讀常量。
C語言中動態內存管理方式
malloc/calloc/realloc/free
void Test ()
{
int* p1 = (int*) malloc(sizeof(int));
free(p1);
// 1.malloc/calloc/realloc的區別是什么?
int* p2 = (int*)calloc(4, sizeof (int));
int* p3 = (int*)realloc(p2, sizeof(int)*10);
// 這里需要free(p2)嗎?
free(p3 );
}
C++內存管理方式
C 語言內存管理方式在 C++ 中可以繼續使用,但有些地方就無能為力,而且使用起來比較麻煩,因此 C++ 又提 出了自己的內存管理方式:通過 new 和 delete 操作符進行動態內存管理 。
new/delete操作內置類型
void Test()
{
// 動態申請一個int類型的空間
int* ptr4 = new int;
// 動態申請一個int類型的空間并初始化為10
int* ptr5 = new int(10);
// 動態申請10個int類型的空間
int* ptr6 = new int[10];
delete ptr4;
delete ptr5;
delete[] ptr6;
}
注意:申請和釋放單個元素的空間,使用 new 和 delete 操作符,申請和釋放連續的空間,使用 new[] 和 delete[] ,注意:匹配起來使用。
new和delete操作自定義類型
class A
{
public:
A(int a = 0)
: _a(a)
{
cout << "A():" << this << endl;
}
~A()
{
cout << "~A():" << this << endl;
}
private:
int _a;
};
int main()
{
// new/delete 和 malloc/free最大區別是 new/delete對于【自定義類型】除了開空間還會調用構
造函數和析構函數
A* p1 = (A*)malloc(sizeof(A));
A* p2 = new A(1);
free(p1);
delete p2;
// 內置類型是幾乎是一樣的
int* p3 = (int*)malloc(sizeof(int)); // C
free(p3);
delete p4;
A* p5 = (A*)malloc(sizeof(A)*10);
A* p6 = new A[10];
free(p5);
delete[] p6;
return 0;
}
注意:在申請自定義類型的空間時, new 會調用構造函數, delete 會調用析構函數,而 malloc 與 free 不會