* 实验内容:探究C++的内存分区模型
* 1)静态全局变量(初始化、不初始化)、静态局部变量
* 2)常量(不同类型)
* 3)全局变量(初始化、不初始化)
* 4)局部变量(main函数中)
* 实验结果:静态变量(全局、局部)和全局变量都存放在全局区,根据是否初始化分区存放,全局常量存放在全局区,局部常量存放在栈区。
* 实验代码
#include <iostream>
using namespace std;
// 静态全局变量(初始化、不初始化)
static int s_g_a = 10;
static int s_g_b;
// 全局变量(初始化,不初始化)
int g_a = 10;
int g_b;
// 常量
const int c_g_a = 10;
// const int c_g_b;
const string str1 = "hello";
const string str2;
int main() {
// 静态局部变量
static int s_p_a = 10;
static int s_p_b;
int a = 100;
const string str = "bonjour";
cout << "初始化后的静态变量、全局变量应该地址在一起,在data段" << endl;
cout << "静态全局变量(初始化后)的地址为:" << & s_g_a << endl;
cout << "全局变量(初始化后)的地址为:" << &g_a << endl;
cout << "静态局部变量(初始化后)的地址为:" << &s_p_a << endl;
cout << "---------------------------------------------------------" << endl;
cout << "未初始化的静态变量、全局变量应该地址在一起,在bss段" << endl;
cout << "静态全局变量(未初始化)的地址为:" << &s_g_b << endl;
cout << "全局变量(未初始化)的地址为:" << &g_b << endl;
cout << "静态局部变量(未初始化)的地址为:" << &s_p_b << endl;
cout << "---------------------------------------------------------" << endl;
cout << "常量也在全局区,但不知道内存分配具体规律" << endl;
cout << "全局int型常量(初始化后)的地址为:" << &c_g_a << endl;
cout << "全局string型常量(初始化后)的地址为:" << &str1 << endl;
cout << "全局string型常量(未初始化)的地址为:" << &str2 << endl;
cout << "局部常量应该在栈区,最高位地址" << endl;
cout << "局部int变量(初始化后)的地址为:" << &a << endl;
cout << "局部string常量(初始化后)的地址为:" << &str << endl;
cout << "---------------------------------------------------------" << endl;
return 0;
}