C++程序运行时内存布局之----------局部变量,全局变量,静态变量,函数代码,new出来的变量
声明两点:
(1)开发测试环境为VS2010+WindowsXP32位;
(2)内存布局指的是虚拟内存地址,不是物理地址。
1.测试代码
#include <iostream>
using namespace std;
int g_int_a;
int g_int_b;
void f_1()
{
cout<<"I'm f_1"<<endl;
}
void f_2()
{
cout<<"I'm f_2"<<endl;
}
int main(int argc, char** argv)
{
int a;
int b;
static int sa;
static int sb;
int* h1 = new int;
int* h2 = new int;
cout<<"argc的地址是 :"<<std::hex<<std::showbase<<&argc<<endl;
cout<<"argv的地址是 :"<<std::hex<<std::showbase<<&argv<<endl;
cout<<"g_int_a的地址是:"<<std::hex<<std::showbase<<&g_int_a<<endl;
cout<<"g_int_b的地址是:"<<std::hex<<std::showbase<<&g_int_b<<endl;
cout<<"a的地址是 :"<<std::hex<<std::showbase<<&a<<endl;
cout<<"b的地址是 :"<<std::hex<<std::showbase<<&b<<endl;
cout<<"f_1()的地址是 :"<<std::hex<<std::showbase<<f_1<<endl;
cout<<"f_2()的地址是 :"<<std::hex<<std::showbase<<f_2<<endl;
cout<<"main()的地址是 :"<<std::hex<<std::showbase<<main<<endl;
cout<<"静态变量sa地址 :"<<std::hex<<std::showbase<<&sa<<endl;
cout<<"静态变量sb地址 :"<<std::hex<<std::showbase<<&sb<<endl;
cout<<"h1的地地址 :"<<std::hex<<std::showbase<<&h1<<endl;
cout<<"h2的地址 :"<<std::hex<<std::showbase<<&h2<<endl;
cout<<"new出来*h1地址:"<<std::hex<<std::showbase<<h1<<endl;
cout<<"new出来*h2地址:"<<std::hex<<std::showbase<<h2<<endl;
cin>>a;
}
2.测试结果与布局图
运行结果:
内存分析:
全局变量,静态变量----存于数据区;
局部变量,函数形参----存于stack;
函数代码----------------存于代码区;
new出来的变量--------存于heap。