C++程序运行时内存布局之----------局部变量,全局变量,静态变量,函数代码,new出来的变量

来源:互联网 发布:同时删除多个表的数据 编辑:程序博客网 时间:2024/05/21 07:49

转自:http://blog.csdn.net/smstong/article/details/6578243

声明两点:

(1)开发测试环境为VS2010+WindowsXP32位;

(2)内存布局指的是虚拟内存地址,不是物理地址。

 

1.测试代码

[cpp:nogutter] view plaincopy
  1. #include <iostream>  
  2. using namespace std;  
  3. int g_int_a;  
  4. int g_int_b;  
  5. void f_1()  
  6. {  
  7.     cout<<"I'm f_1"<<endl;  
  8. }  
  9. void f_2()  
  10. {  
  11.     cout<<"I'm f_2"<<endl;  
  12. }  
  13. int main(int argc, char** argv)  
  14. {  
  15.     int a;  
  16.     int b;  
  17.     static int sa;  
  18.     static int sb;  
  19.     int* h1 = new int;  
  20.     int* h2 = new int;  
  21.     cout<<"argc的地址是   :"<<std::hex<<std::showbase<<&argc<<endl;  
  22.     cout<<"argv的地址是   :"<<std::hex<<std::showbase<<&argv<<endl;  
  23.     cout<<"g_int_a的地址是:"<<std::hex<<std::showbase<<&g_int_a<<endl;  
  24.     cout<<"g_int_b的地址是:"<<std::hex<<std::showbase<<&g_int_b<<endl;  
  25.     cout<<"a的地址是      :"<<std::hex<<std::showbase<<&a<<endl;  
  26.     cout<<"b的地址是      :"<<std::hex<<std::showbase<<&b<<endl;  
  27.     cout<<"f_1()的地址是  :"<<std::hex<<std::showbase<<f_1<<endl;  
  28.     cout<<"f_2()的地址是  :"<<std::hex<<std::showbase<<f_2<<endl;  
  29.     cout<<"main()的地址是 :"<<std::hex<<std::showbase<<main<<endl;  
  30.     cout<<"静态变量sa地址 :"<<std::hex<<std::showbase<<&sa<<endl;  
  31.     cout<<"静态变量sb地址 :"<<std::hex<<std::showbase<<&sb<<endl;  
  32.     cout<<"h1的地地址     :"<<std::hex<<std::showbase<<&h1<<endl;  
  33.     cout<<"h2的地址       :"<<std::hex<<std::showbase<<&h2<<endl;  
  34.     cout<<"new出来*h1地址:"<<std::hex<<std::showbase<<h1<<endl;  
  35.     cout<<"new出来*h2地址:"<<std::hex<<std::showbase<<h2<<endl;  
  36.     cin>>a;  
  37. }  

2.测试结果与布局图

运行结果:

内存分析:

全局变量,静态变量----存于数据区;

局部变量,函数形参----存于stack;

函数代码----------------存于代码区;

new出来的变量--------存于heap。

 


原创粉丝点击