(转)程序是怎么在内存中存储的

一个程序占有的内存分为5类:

1. 全局/静态数据区---->对应  .data数据段

2.常量数据区--> .rdata只读数据段

3.代码区--->  .text代码段 (存储代码)

4.栈

5.堆

 

 

内存存储情况:

1. 全局/静态数据区---> 全局/静态数据

2.常量数据区(.rdata)-->常量字符串

3.栈---->自动变量或者局部变量,以及传递的函数参数

4.堆--->用户控制  new/malloc出来的内存,注意内存泄露问题

 

 

  下面通过具体代码查看数据的存储问题:


        

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. int nGlobal = 200;  
  4. int main()  
  5. {  
  6.     char *pLocalString1 = "LocalString1";  
  7.     const char *pLocalString2 = "LocalString2";  
  8.     static int nLocalStatic = 100;  
  9.     int nLocal = 1;  
  10.     const int nLocalConst = 20;  
  11.     int * pNew = (int *)malloc(sizeof(int)*5);;  
  12.     char *pMalloc = (char *)malloc(1);  
  13.     //全局/静态数据区  
  14.     printf("全局/静态数据区:/n");  
  15.     printf("global variable:            0x%x/n", &nGlobal);  
  16.     printf("static variable:            0x%x/n/n", &nLocalStatic);  
  17.     //常量区  
  18.     printf("常量区:/n");  
  19.     printf("pLocalString1 variable:     0x%x/n", pLocalString1);  
  20.     printf("pLocalString2 variable:     0x%x/n", pLocalString2);  
  21.     printf("nLocalConst variable:       0x%x/n/n", nLocalConst);  
  22.     //堆  
  23.     printf("堆:/n");  
  24.     printf("new  variable:              0x%x/n", pNew);  
  25.     printf("malloc variable:            0x%x/n/n", pMalloc);  
  26.     //栈  
  27.     printf("栈:/n");  
  28.     printf("pointer pnew variable:      0x%x/n", &pNew);  
  29.     printf("pointer malloc variable:    0x%x/n", &pMalloc);  
  30.     printf("nLocal variable:            0x%x/n", &nLocal);  
  31.     printf("pointer pLocalString1 variable: 0x%x/n", &pLocalString1);  
  32.     printf("pointer pLocalString2 variable: 0x%x/n", &pLocalString2);  
  33.     printf("nLocalConst variable:           0x%x/n/n", &nLocalConst);  
  34.     return 0;  
  35. }  

 

下面是运行结果:

 

我们可以看到栈和堆的内存都存在内存对齐的。 堆的内存是按照34个字节对齐(我的机器是这样的)的。

下面是各个数据所在区间的对应关系:

站在巨人的肩膀上:http://blog.csdn.net/icekingson/article/details/6461629

转载于:https://my.oschina.net/topdstar/blog/540021

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值