網站首頁 編程語言 正文
前言
在我們日常寫代碼的過程中,我們對內存空間的需求有時候在程序運行的時候才能知道,這時候我們就需要使用動態開辟內存的方法。
1、C/C++程序的內存開辟
首先我們先了解一下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));
int* ptr3 = (int*)realloc(ptr2, sizeof(int) * 4);
free(ptr1);
free(ptr3);
}
- 1. 棧區(stack):在執行函數時,函數內局部變量的存儲單元都可以在棧上創建,函數執行結束時這些存儲單元自動被釋放。棧內存分配運算內置于處理器的指令集中,效率很高,但是分配的內存容量有限。 棧區主要存放運行函數而分配的局部變量、函數參數、返回數據、返回地址等。
- 2. 堆區(heap):一般由程序員分配釋放, 若程序員不釋放,程序結束時可能由OS回收 。分配方式類似于鏈表。
- 3. 數據段(靜態區)(static)存放全局變量、靜態數據。程序結束后由系統釋放。
- 4. 代碼段:存放函數體(類成員函數和全局函數)的二進制代碼。
這幅圖中,我們可以發現普通的局部變量是在棧上分配空間的,在棧區中創建的變量出了作用域去就會自動銷毀。但是被static修飾的變量是存放在數據段(靜態區),在數據段上創建的變量直到程序結束才銷毀,所以數據段上的數據生命周期變長了。
2.C語言中動態內存管理方式:malloc/calloc/realloc/free
在C語言中,我們經常會用到malloc,calloc和realloc來進行動態的開辟內存;同時,C語言還提供了一個函數free,專門用來做動態內存的釋放和回收。其中他們三個的區別也是我們需要特別所強調區別的。
2.1malloc、calloc、realloc區別?
malloc函數是向內存申請一塊連續可用的空間,并返回指向這塊空間的指針。
calloc與malloc的區別只在于calloc會在返回地址之前把申請的空間的每個字節初始化為0。
realloc函數可以做到對動態開辟內存大小的調整。
我們通過這三個函數的定義也可以進行功能的區分:
void Test ()
{
int* p1 = (int*) malloc(sizeof(int));
free(p1);
int* p2 = (int*)calloc(4, sizeof (int));
int* p3 = (int*)realloc(p2, sizeof(int)*10);
free(p3 );
}
3.C++內存管理方式
我們都知道,C++語言是兼容C語言的,因此C語言中內存管理方式在C++中可以繼續使用。但是有些地方就無能為力了,并且使用起來也可能比較麻煩。因此,C++擁有自己的內管管理方式:通過new和delete操作符進行動態內存管理。
3.1 new/delete操作內置類型
int main()
{
// 動態申請一個int類型的空間
int* ptr1 = new int;
// 動態申請一個int類型的空間并初始化為10
int* ptr2 = new int(10);
// 動態申請3個int類型的空間(數組)
int* ptr3 = new int[3];
// 動態申請3個int類型的空間,初始化第一個空間值為1
int* ptr4 = new int[3]{ 1 };
delete ptr1;
delete ptr2;
delete[] ptr3;
delete[] ptr4;
return 0;
}
??我們首先通過畫圖分析進行剖析代碼:
我們在監視窗口看看這3個變量
注意:申請和釋放單個元素的空間,使用new和delete操作符,申請和釋放連續的空間,使用new[]和delete[],要匹配起來使用。
3.2 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()
{
A* p1 = (A*)malloc(sizeof(A));
A* p2 = new A(1);
free(p1);
delete p2;
return 0;
}
在這段代碼中,p1是我們使用malloc開辟的,p2是通過new來開辟的。我們編譯運行這段代碼。
發現輸出了這兩句,那這兩句是誰調用的呢?我們通過調試逐語句來分析這個過程
內置類型區別
注意:在申請自定義類型的空間時,new會自動調用構造函數,delete時會調用析構函數,而malloc和free不會。
3.3new和malloc處理失敗
int main()
{
void* p0 = malloc(1024 * 1024 * 1024);
cout << p0 << endl;
//malloc失敗,返回空指針
void* p1 = malloc(1024 * 1024 * 1024);
cout << p1 << endl;
try
{
//new失敗,拋異常
void* p2 = new char[1024 * 1024 * 1024];
cout << p2 << endl;
}
catch (const exception& e)
{
cout << e.what() << endl;
}
return 0;
}
?我們能夠發現,malloc失敗時會返回空指針,而new失敗時,會拋出異常。
4.operator new與operator delete函數
4.1 operator new與operator delete函數
C++標準庫還提供了operator new和operator delete函數,但是這兩個函數并不是對new和delete的重載,operator new和operator delete是兩個庫函數。(這里C++大佬設計時這樣取名確實很容易混淆)
4.1.1 我們看看operator new庫里面的源碼
void* __CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc) {
// try to allocate size bytes
void* p;
while ((p = malloc(size)) == 0)
if (_callnewh(size) == 0)
{
// report no memory
// 如果申請內存失敗了,這里會拋出bad_alloc 類型異常
static const std::bad_alloc nomem;
_RAISE(nomem);
}
return (p);
}
庫里面operator new的作用是封裝了malloc,如果malloc失敗,拋出異常。
4.1.2 operator delete庫里面的源碼
該函數最終是通過free來釋放空間的
//operator delete 源碼
void operator delete(void* pUserData) {
_CrtMemBlockHeader* pHead;
RTCCALLBACK(_RTC_Free_hook, (pUserData, 0));
if (pUserData == NULL)
return;
_mlock(_HEAP_LOCK); /* block other threads */
__TRY
/* get a pointer to memory block header */
pHead = pHdr(pUserData);
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
_free_dbg(pUserData, pHead->nBlockUse);
__FINALLY
_munlock(_HEAP_LOCK); /* release other threads */
__END_TRY_FINALLY
return;
}
/*
free的實現
*/
#define free(p) _free_dbg(p, _NORMAL_BLOCK)
4.1.3 operator new和operator delete的價值(重點)
class A {
public:
A(int a = 0)
: _a(a)
{
cout << "A():" << this << endl;
}
~A()
{
cout << "~A():" << this << endl;
}
private:
int _a;
};
int main()
{
//跟malloc功能一樣,失敗以后拋出異常
A* ps1 = (A*)operator new(sizeof(A));
operator delete(ps1);
A* ps2 = (A*)malloc(sizeof(A));
free(ps2);
A* ps3 = new A;
delete ps3;
return 0;
}
我們使用new的時候,new要開空間,要調用構造函數。new可以轉換成call malloc,call 構造函數。但是call malloc 一旦失敗,會返回空指針或者錯誤碼。在面向對象的語言中更喜歡使用異常。而operator new相比較malloc的不同就在于如果一旦失敗會拋出異常,因此new的底層實現是調用operator new,operator new會調用malloc(如果失敗拋出異常),再調用構造函數。
我們通過匯編看一下ps3
operator delete同理。
總結:通過上述兩個全局函數的實現知道,operator new 實際也是通過malloc來申請空間,如果malloc申請空間成功就直接返回,否則執行用戶提供的空間不足應對措施,如果用戶提供該措施就繼續申請,否則就拋異常。operator delete 最終是通過free來釋放空間的。
4.2 重載operator new 與 operator delete(了解)
專屬的operator new技術,提高效率。應用:內存池
class A {
public:
A(int a = 0)
: _a(a)
{
cout << "A():" << this << endl;
}
// 專屬的operator new
void* operator new(size_t n)
{
void* p = nullptr;
p = allocator<A>().allocate(1);
cout << "memory pool allocate" << endl;
return p;
}
void operator delete(void* p)
{
allocator<A>().deallocate((A*)p, 1);
cout << "memory pool deallocate" << endl;
}
~A()
{
cout << "~A():" << this << endl;
}
private:
int _a;
};
int main()
{
int n = 0;
cin >> n;
for (int i = 0; i < n; ++i)
{
A* ps1 = new A; //operator new + A的構造函數
}
return 0;
}
注意:一般情況下不需要對 operator new 和 operator delete進行重載,除非在申請和釋放空間時候有某些特殊的需求。比如:在使用new和delete申請和釋放空間時,打印一些日志信息,可以簡單幫助用戶來檢測是否存在內存泄漏。
5.new 和 delete 的實現原理
5.1 內置類型
如果申請的是內置類型的空間,new和malloc,delete和free基本類似,不同的地方是:new/delete申請和釋放的是單個元素的空間,new[]和delete[]申請的是連續空間,而且new在申請空間失敗時會拋異常,malloc會返回NULL。
5.2 自定義類型
5.2.1 new原理
- 1、調用operator new函數申請空間
- 2、再調用構造函數,完成對對象的構造。
5.2.2 delete原理
- 1、先調用析構函數,完成對對象中資源的清理工作。
- 2、調用operator delete函數釋放對象的空間
5.2.3?new T[N]原理
- 1、先調用operator new[]函數,在operator new[]中世紀調用operator new函數完成N個對象空間的申請
- 2、在申請的空間上執行N次構造函數
5.2.4?delete[]原理
- 1、在釋放的對象空間上執行N次析構函數,完成對N個對象中資源的清理
- 2、調用operator delete[]釋放空間,實際在operator delete[]中調用operator delete來釋放空間。
6.malloc/free和new/delete的異同
6.1malloc/free和new/delete的共同點
都是從堆上申請空間,都需要用戶手動釋放空間。
6.2malloc/free和new/delete的不同點
- 1:malloc和free是函數,new和delete是操作符
- 2:malloc申請的空間不會初始化,new可以初始化
- 3:malloc申請空間時,需要手動計算空間大小并傳遞,new只需在其后跟上空間的類型即可,如果是多個對象,[]中指定對象個數即可
- 4:malloc的返回值為void*, 在使用時必須強轉,new不需要,因為new后跟的是空間的類型
- 5:malloc申請空間失敗時,返回的是NULL,因此使用時必須判空,new不需要,但是new需要捕獲異常
- 6:申請自定義類型對象時,malloc/free只會開辟空間,不會調用構造函數與析構函數,而new在申請空間后會調用構造函數完成對象的初始化,delete在釋放空間前會調用析構函數完成空間中資源的清理
原文鏈接:https://blog.51cto.com/xingyuli/5509008
相關推薦
- 2023-03-04 linux服務器CPU飆高排查分析_Linux
- 2022-06-12 Python利用Matplotlib庫實現繪制餅形圖_python
- 2022-05-18 C語言實現學生宿舍信息管理系統_C 語言
- 2022-03-28 Python中selenium_webdriver下拉框操作指南_python
- 2021-11-03 Linux系統下grub.cfg文件損壞修復步驟_Linux
- 2022-09-30 ASP.NET?MVC為用戶創建專屬文件夾_實用技巧
- 2021-12-18 C++?STL容器詳解之紅黑樹部分模擬實現_C 語言
- 2022-08-27 python中DataFrame數據合并merge()和concat()方法詳解_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支