您的位置:首页 > 编程语言

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

2015-04-08 15:42 218 查看
一个程序占有的内存分为5类:

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

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

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

4.栈

5.堆

 

 

内存存储情况:

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

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

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

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

 

 

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



        

[b][cpp] view
plaincopy[/b]

#include <stdio.h>  

#include <stdlib.h>  

int nGlobal = 200;  

int main()  

{  

    char *pLocalString1 = "LocalString1";  

    const char *pLocalString2 = "LocalString2";  

    static int nLocalStatic = 100;  

    int nLocal = 1;  

    const int nLocalConst = 20;  

    int * pNew = (int *)malloc(sizeof(int)*5);;  

    char *pMalloc = (char *)malloc(1);  

    //全局/静态数据区  

    printf("全局/静态数据区:/n");  

    printf("global variable:            0x%x/n", &nGlobal);  

    printf("static variable:            0x%x/n/n", &nLocalStatic);  

    //常量区  

    printf("常量区:/n");  

    printf("pLocalString1 variable:     0x%x/n", pLocalString1);  

    printf("pLocalString2 variable:     0x%x/n", pLocalString2);  

    printf("nLocalConst variable:       0x%x/n/n", nLocalConst);  

    //堆  

    printf("堆:/n");  

    printf("new  variable:              0x%x/n", pNew);  

    printf("malloc variable:            0x%x/n/n", pMalloc);  

    //栈  

    printf("栈:/n");  

    printf("pointer pnew variable:      0x%x/n", &pNew);  

    printf("pointer malloc variable:    0x%x/n", &pMalloc);  

    printf("nLocal variable:            0x%x/n", &nLocal);  

    printf("pointer pLocalString1 variable: 0x%x/n", &pLocalString1);  

    printf("pointer pLocalString2 variable: 0x%x/n", &pLocalString2);  

    printf("nLocalConst variable:           0x%x/n/n", &nLocalConst);  

    return 0;  

}  



 

下面是运行结果:



 

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



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



转自:http://blog.csdn.net/icekingson/article/details/6461629
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息