[C++应用程序性能优化]程序使用内存区

本文通过一个简单的C++程序示例,详细介绍了计算机程序运行时内存的各个区域:全局/静态数据区、常量数据区、栈和堆的区别与特点。通过对不同变量类型的地址输出,帮助读者理解各种类型的数据如何被分配到不同的内存区域。
/************************************************************************
全局/静态数据区:存储全局变量及静态变量(包括全局静态变量和局部静态变量)
常量数据区:存储程序中常量字符串等代码区
栈:存储自动变量或局部变量,以及传递的函数参数等
堆:用户程序控制的存储区,存储动态产生的数据
************************************************************************
//***VS2005 TEST***/
#include <stdio.h>
#include <stdlib.h>
int nGlobal = 100;
int main()
{ 
 char *pLcocalString1 = "LocalString1"; // 4字节对齐, 13个字节,则为16个字节
 const char *pLcocalString2 = "LocalString2"; //
 static int nLocalStatic = 100;
 int nLocal = 1;
 const int nLocalConst = 20;
 int *pNew = new int[5]; // 16字节对齐
 char *pMalloc = (char*)malloc(1);
 printf("global variable: 0x%x\n", &nGlobal); // 0x417000
 printf("static variable: 0x%x\n", &nLocalStatic); // 0x417004
 printf("local expression 1: 0x%X\n", pLcocalString1); // 0x4158A4 (与下一个相差20个字节。。。)
 printf("local expression (const): 0x%X\n", pLcocalString2); // 0x4158B8
 printf("\n");
 printf("new: 0x%x\n", pNew); // 0x3f5e38 (4*5 = 20字节,16字节对齐,则为32)(这里为5*16...)
 printf("malloc:0x%x\n", pMalloc); // 0x3f5e88
 printf("\n");
 printf("local pointer(pNew): 0x%x\n", &pNew); // 0x12ff30
 printf("local pointer(pLocalString2): 0x%x\n", &pLcocalString2); // 0x12ff54
 printf("local pointer(pLocalString1): 0x%x\n", &pLcocalString1); // 0x12ff60
 printf("local variable(nLocal): 0x%x\n", &nLocal); // 0x12ff48
 printf("local variable(pMalloc): 0x%x\n", &pMalloc); // 0x12ff24
 printf("local const variable: 0x%x\n", &nLocalConst); // 0x12ff3c
 system("pause");
 return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值