學了馮諾依曼體系結構,我們知道: 硬件決定軟件行為,數據都是圍繞內存流動的。
可想而知,內存是多么重要。當然,我們這里說的內存是虛擬內存(詳情看Linxu壹之型)。
1.C/C++內存布局

2.C語言動態內存管理方式
申請內存 : malloc/calloc/realloc
釋放 : free
malloc/calloc/realloc的區別:
//申請大小為size的內存塊 void* malloc (size_t size); //申請大小為num*size的內存塊,並將每個元素初始化為0 void* calloc (size_t num, size_t size); //ptr為NULL,申請空間類似於malloc //ptr不為NULL,則將ptr指向空間改變大小為size,並且如果改變的空間遠大於舊空間,會申請新內存塊,並將原數據拷貝過來,釋放舊空間,返回新地址 void* realloc (void* ptr, size_t size);
3.C++動態內存管理

在C++中,申請動態內存不再是函數,而是操作符。
注意,申請釋放單個元素的空間用new和delete,申請釋放連續的空間用new[]和delete[]。
那么new/delete和malloc/free到底有什么區別呢? 下面,我們做個測試:
#include<iostream>
#include<malloc.h>
using namespace std;
class Test
{
public:
Test()
: _data(0)
{
cout << "Test():" << this << endl;
}
~Test()
{
cout << "~Test():" << this << endl;
}
private:
int _data;
};
void Test2()
{
// 申請單個Test類型的空間
Test* p1 = (Test*)malloc(sizeof(Test));
free(p1);
// 申請10個Test類型的空間
Test* p2 = (Test*)malloc(sizeof(Test) * 10);
free(p2);
}
void Test3()
{
// 申請單個Test類型的對象
Test* p1 = new Test;
delete p1;
// 申請10個Test類型的對象
Test* p2 = new Test[10];
delete[] p2;
}
int main()
{
Test2();
Test3();
getchar();
return 0;
}
測試結果如下:

我們可以得到結果: new會先申請空間,再調用構造函數,delete會先調用析構函數,再釋放空間。而malloc/free不會調用構造/析構函數。
4.new/delete原理
知道了new/delete的用法和特點,接下來開始了解他們的底層原理。
new和delete是用戶進行動態內存申請和釋放的操作符,operator new 和operator delete是系統提供的全局函數。
new在底層調用operator new函數申請空間,delete在底層通過operator delete函數釋放空間。
以下是operator new偽代碼:

以下是operator delete偽代碼:

由此,我們知道operator new和operator delete底層調用了malloc和free,所以,調用關系如下:

總結:

