内存分区的意义:
不同类型的数据存放在不同的分区,赋予不同的生命周期,使编程更加灵活。
在程序编译后,生成了exe可执行程序,未执行该程序前分为代码区与全局区。
1、代码区:由操作系统管理
存放二进制代码。
共享性:频繁执行的程序,只需要在内存中存一份代码就可以。
只读性:防止程序意外修改了它的指令
2、全局区:程序结束后有操作系统释放
全局区存放全局变量,静态变量。
全局区包含常量区,存放字符串常量,const修饰的全局变量(全局常量)
const修饰的局部变量(局部常量)不存放在全局区,存放在栈区。
我们通过代码输出地址一下各种类型的变量,常量存放在内存中的区域。
#include<iostream>
using namespace std;
int a = 10;
int b = 11;
const int c_a = 10;
const int c_b = 10;
static int s_a = 10;
static int s_b = 10;
int main()
{
int j_a = 10;
int j_b = 10;
const int c_j_a = 10;
const int c_j_b = 10;
string s = "hello world";
static int s_c = 10;
cout << "全局变量a的地址 " << (int)&a << endl;
cout << "全局变量b的地址 " << (int)&b << endl;
cout << "静态变量a的地址 " << (int)&s_a << endl;
cout << "静态变量b的地址 " << (int)&s_b << endl;
cout << "静态变量c的地址 " << (int)&s_c << endl;
cout << endl;
cout << "字符串常量的地址 " << (int)&"hello world" << endl;
cout << "全局常量a的地址 " << (int)&c_a << endl;
cout << "全局常量b的地址 " << (int)&c_b << endl;
cout << endl;
cout << endl;
cout << "字符串变量s的地址 " << (int)&s << endl;
cout << "局部变量a的地址 " << (int)&j_a << endl;
cout << "局部变量b的地址 " << (int)&j_b << endl;
cout << "局部常量a的地址 " << (int)&c_j_a << endl;
cout << "局部常量b的地址 " << (int)&c_j_b << endl;
}
运行结果如下:
我们可以看到,全局变量、静态变量、字符串常量,全局常量都是放在一起的,在全局区。
通过地址我们可以推测,在全局区中,全局变量,静态变量在一个小区域中,全局常量在一个区域中,字符串常量在另一个区域中。
局部变量放在一起,在栈区。
3、栈区:由编译器分配释放
存放函数的参数值,局部变量等。
不要返回局部变量的地址。
4、堆区:由程序员自己分配释放
在C++中主要利用new、delete来开辟、释放内存。
若程序员不释放,程序结束时由操作系统回收。