内存分区
C++的内存划分为栈区、堆区、全局区/静态区、常量存储区、代码区、映射区和一些其他的小东西
虚函数表比较特殊,不同的平台存放的位置不同,gcc编译器将虚表放在常量段
栈区
由系统进行内存的管理
说明:主要存放函数的参数、局部变量以及局部常量。栈区由系统进行内存管理,在函数完成执行,系统自行释放栈区内存,不需要用户管理。整个程序的栈区的大小可以在编译器中由用户自行设定,默认的栈区大小为3M。
#include<iostream>
using namespace std;
void test(int c)
{
int d = c;
cout << "c:" << &c << endl;
cout << "d:" << &d << endl;
}
int h = 10;
int main()
{
int a = 10;
const int b = 100;
cout << "a:" << &a << endl;
cout << "b:" << &b << endl;
test(a);
cout << "h:" << &h << endl;
return 0;
}
//a:00EFFEC4
//b:00EFFEB8
//c:00EFFDE4
//d:00EFFDD0
//h:004E901C //用全局变量来做对比
堆区
由用户手动申请,手动释放
说明:使用malloc、new(本质也是malloc)等申请的内存。一定要手动释放!!
全局区/静态区
主要存放静态变量及全局变量,里面又分为.data段和.bss段
初始化了的放在.data段,未初始化的放在.bss段(未初始化则默认为0,若初始化为0也是放在这里)
#include <iostream>
using namespace std;
int a1;
int a2 = 10;
int main()
{
static int b1;
static int b2 = 10;
cout << &a1 << endl;
cout << &a2 << endl;
cout << &b1 << endl;
cout << &b2 << endl;
a1 = 10;
b1 = 10;
cout << &a1 << endl;
cout << &b1 << endl;
int c;
cout << &c << endl;
system("pause");
return 0;
}
//a1:0016938C
//a2:00169004
//b1:00169390
//b2:00169008
//a1:0016938C
//b2:00169390
//c :010FFBF8 //对比
常量存储区
存放常量字符串,程序结束时由系统释放。比如我们定义char * p = “Hello World”; 这里的“Hello World”就是在字符串常量中,最终系统会自动释放
代码区
存放程序体的二进制代码。比如我们写的函数,都是在代码区的
映射区
存储动态链接库以及调用mmap函数进行的文件映射