首页 > 代码库 > [c++]程序的内存划分理解

[c++]程序的内存划分理解

  • 全局和静态数据区:用于存放全局变量和静态变量(全局变量和局部变量)
  • 常量数据区:用于存放常量数据
  • 代码区:用于存储代码
  • 栈:用于局部变量和函数参数
  • 堆:程序员申请(程序员控制的部分,new/delete
#include <stdio.h>
#include <stdlib.h>

int gGlobal=100; // global 

int main(void){
        char *pLocalString1="LocalString1";
        const char *pLocalString2="LocalString2";
        static int nLocalStatic=100;
        
        int nLocal=10;
        const int nLocalConst=20;
        
        int *pNew = new int[5];
        char *pMalloc = (char*)malloc(1);
        
        
        printf("global var            0x%x\n",&gGlobal);
        printf("static var            0x%x\n",&nLocalStatic);
        printf("\n");
        printf("local var1                    0x%x\n",&pLocalString1);
        printf("local var2(const)            0x%x\n",&pLocalString2);
        
        printf("\n");
        
        printf("pNew                     0x%x\n",pNew);
        printf("pMalloc             0x%x\n",pMalloc);
        
        pLocalString1[1]=a;//error 字符常量,数据定义好后,不能在修改.该地址,在编译前已经确定好
        printf("\n");
        
        printf("local point(pNew)                     0x%x\n",&pNew);
        printf("local point(pMalloc)              0x%x\n",&pMalloc);
        printf("local point(pLocalString1)                     0x%x\n",&pLocalString1);
        printf("local point(pLocalString2)                     0x%x\n",&pLocalString2);
        printf("local point(nLocalConst)                     0x%x\n",&nLocalConst);
        printf("local point(nLocal)                     0x%x\n",&nLocal);
        
        
}