内存分区模型
内存在计算机中大致分为四个区域:
- 代码区:存放函数体的二进制代码,由操作系统管理
- 全局区:存放全局变量,静态变量与常量
- 栈区:由编译器自动分配释放,存放函数的参数值,局部变量等
- 堆区:由用户分配释放,若不释放程序结束后由操作系统回收
程序运行前
程序编译后,生成exe可执行程序,未执行前分为两个区域
代码区:
- 存放CPU执行的机器指令
- 代码区是共享的,对于频繁执行的程序,只需要在内存中有一份代码即可
- 代码区是只读的,防止程序意外修改他的指令
全局区:
- 存放全局变量、静态变量与常量(不包括const修饰的局部变量)
- 该区域数据在程序结束后由操作系统释放
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| #include <iostream> using namespace std;
int g_a = 10; int g_b = 10;
const int g_c = 10; int main(){ int l_a = 10; int l_b = 10; static int s_a = 10; static int s_b = 10;
cout << "字符串常量的地址:"<< (void*)&"hello world" << endl; const int l_c = 10;
cout <<"局部变量l_a的地址: " << (void*)&l_a << endl; cout <<"局部变量l_b的地址: " << (void*)&l_b << endl; cout <<"静态局部变量s_a的地址: " << (void*)&s_a << endl; cout <<"静态局部变量s_b的地址: " << (void*)&s_b << endl; cout <<"全局变量g_a的地址: " << (void*)&g_a << endl; cout <<"全局变量g_b的地址: " << (void*)&g_b << endl; cout <<"const修饰的全局变量g_c的地址: " << (void*)&g_c << endl; cout <<"const修饰的局部变量l_c的地址: " << (void*)&l_c << endl;
return 0; }
|
输出发现,不同类型的量所在地址位置有较大差异
1 2 3 4 5 6 7 8 9
| 字符串常量的地址:0x404024 局部变量l_a的地址: 0x61fe1c 局部变量l_b的地址: 0x61fe18 静态局部变量s_a的地址: 0x403018 静态局部变量s_b的地址: 0x40301c 全局变量g_a的地址: 0x403010 全局变量g_b的地址: 0x403014 const修饰的全局变量g_c的地址: 0x404004 const修饰的局部变量l_c的地址: 0x61fe14
|
程序运行后
栈区:
由编译器自动分配释放,存放函数参数,局部变量等
不要返回局部变量的地址
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <iostream> using namespace std; int* f(int b){ int a = 10; return &a; } int main(){ int *p = f(100); cout << *p << endl; cout << *p << endl; return 0;
}
|
堆区:
由用户分配释放,若不释放,程序结束后由操作系统回收
使用关键字new开辟内存
1 2 3 4 5 6 7 8 9 10 11 12
| #include <iostream> using namespace std; int* f(){ int *p = new int(10); return p; } int main(){ int *p = f(); cout << *p << endl; cout <<"地址: " << (void*)p << endl; return 0; }
|
关键字new
C++中,使用new关键字在堆区开辟空间,使用delete关键字释放内存
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include <iostream> using namespace std;
int main(){ int* p = new int(10); int* arr = new int[10]; for (int i = 0;i<10;i++){ arr[i]=i; } cout << *p << endl; for (int i = 0;i<10;i++){ cout << arr[i] << " "; } delete p; delete[] arr; return 0; }
|