文章目錄
- c/c++內存管理
- c語言動態內存管理
- c++動態內存管理
- new/delete自定義類型妙用
- operator new和operator delete
- malloc/new,free/delete區別
c/c++內存管理
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));//開辟4個int空間,并初始化0,int* ptr3 = (int*)realloc(ptr2, sizeof(int) * 4);free(ptr1);free(ptr3);}
1,棧,又叫堆棧,存儲非局部變量/函數參數/返回值,向下生長,
2,堆,存儲動態開辟數據,用于程序運行的內存分配,向上生長,
3,數據段,存儲全局變量,靜態變量,
4,代碼段,存儲可執行代碼/只讀常量,
c語言動態內存管理
#include <stdio.h>
#include <stdlib.h>
int main()
{int* p1 = (int*)malloc(sizeof(int) * 5);free(p1);int* p2 = (int*)malloc(sizeof(int) * 5);//分配5個int內存并初始化0,int* p3 = (int*)realloc(p2,sizeof(int) * 10);//將p2擴大到10個內存,也可以縮小,p2 = p3;free(p2);return 0;
}
calloc對開辟的內存直接初始化0,realloc可以擴充或縮小數組
c++動態內存管理
有關C語言的動態內存函數在c++還能用,但用起來麻煩,所以c++提出自己的動態內存管理,
:通過new和delete操作符進行動態內存管理
#include <iostream>
using namespace std;
int main()
{int* p1 = new int;int* p2 = new int(10);int* p3 = new int[4];delete p1;delete p2;delete[] p3;return 0;
}
p1正是開辟一個int內存;
p2開辟1個int內存并初始化為10,記住用括號,
p3開辟4個int內存,記住用方括號,
p1,p2正常刪除,p3 delete后面加方括號
申請開辟連續空間和釋放,[]匹配使用
new/delete自定義類型妙用
#include <iostream>
using namespace std;
class A {
public:A(int a=0): _a(a){cout << "A():" <<this<< endl;}~A(){cout << "~A():" <<this<< endl;}
private:int _a;
};
int main()
{A* p1 = (A*)malloc(sizeof(A));free(p1);A* p2 = new A(4);delete p2;A* p3 = new A[5];delete[] p3;return 0;
}
A():000001F1BFF08110
~A():000001F1BFF08110
A():000001F1BFF159E8
A():000001F1BFF159EC
A():000001F1BFF159F0
A():000001F1BFF159F4
A():000001F1BFF159F8
~A():000001F1BFF159F8
~A():000001F1BFF159F4
~A():000001F1BFF159F0
~A():000001F1BFF159EC
~A():000001F1BFF159E8
是的,🚩new與delete對自定義類型可以直接調用構造和析構函數
而malloc和free不會
operator new和operator delete
operator new和operator delete是系統提供的全局函數,
🚩使用操作符new和delete實際上在底層上調用這兩個全局函數來申請和釋放空間,
(實際上operator new也是通過malloc開辟空間,如果成功直接返回,如果空間不足就執行用戶的限制條件,若無限定條件直接報錯,operator delete也是通過free釋放的,同理)
malloc/new,free/delete區別
共同:都能從堆申請空間,并且都要手動釋放
🚩1,new和delete是操作符,那兩是函數,
🚩2,malloc申請空間不會初始化,new會初始化
3,malloc需要自己計算空間大小并傳遞,new只需要在后面加類型即可,
4, malloc需要強轉,因為自己是void*()類型,new只需加空間類型
🚩5,malloc申請空間失敗返回NULL必須判空,new不需要,但需要捕獲異常,
🚩6,申請自定義對象時,new和delete會調用構造和析構函數,那兩不會