C++程序运行时内存布局

声明两点:

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

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

 

1.测试代码

[cpp]  view plain copy
  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。


 

C++程序运行时内存布局之----------空类实例

分类: Windows相关 C/C++   532人阅读  评论(2)  收藏  举报

1.测试代码

[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <bitset>  
  3. using namespace std;  
  4. class CEmpty  
  5. {  
  6. };  
  7. int main(int argc, char** argv)  
  8. {  
  9.     CEmpty *pObjInHeap = new CEmpty();  
  10.     CEmpty objInStack;  
  11.     cout<<"CEmpty类型的对象占用内存大小(字节):"<<sizeof(CEmpty)<<endl;  
  12.     cout<<"堆上分配对象时,对象地址为:"<<std::hex<<std::showbase<<pObjInHeap<<endl;  
  13.     cout<<"栈上分配对象时,对象地址为:"<<std::hex<<std::showbase<<&objInStack<<endl;  
  14.     cout<<"堆上对象的内容是:"<<bitset<8>(*((char*)pObjInHeap))<<endl;  
  15.     cout<<"栈上对象的内容是: "<<bitset<8>(*((char*)(&objInStack)))<<endl;  
  16.     cin>>argc;  
  17. }  

2.运行结果与分析

可见:

(1)空类的对象也占有一个字节的内存空间,以证明自己的存在;

(2)对象既可以建立在stack上,也可以建立在heap上;

(3)这一个字节的值没有规定具体的值是多少。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值