部分程序来源于 冯宏华、徐莹、程远、汪磊等编著<<C++应用程序性能优化>>
日前在阅读<<C++应用程序性能优化>>觉得里面的一些内容非常不错,这里跟大家分享一下。
一个程序占用的内存区一般分为如下5种
1.全局/静态数据区。
2.常数数据区
3.代码区
4.栈
5.堆(动态分配的内存、在C++中需手动收回)
下面通过一个例子来说明各种类型的数据在内存中的位置
#include<iostream>
#include<stdio.h>
using namespace std;
int nGlobal=100;
int main()
{
static int nLocalStatic = 100;
char *pLocalString1 = "LocalString1";
const char *pLocalString2 = "LocalString2";
int nLocal =1;
const int nLocalConst = 1;
int *pNew = new int[5]; //16个字节对齐
char *pMalloc = (char *)malloc(1);
const int nLocalConst2 = 3;
//-------------全局/静态数据区---------------
cout<<"global variable: 0x"<<&nGlobal<<endl; // 0x00474DC0
cout<<"local static variable: Ox"<<&nLocalStatic<<endl; // Ox00474DC4
cout<<endl;
//这里因为内存对齐字符串只有13个字节但两个地址却有16个字节的差距
printf("local string1: 0x%x/n",pLocalString1); // 0x46c1a0
printf("local const string2: 0x%x/n/n",pLocalString2); // 0x46c190
printf("new : 0x%x/n",pNew); // 0x480030
printf("malloc : 0x%x/n/n",pMalloc); // 0x481dd0
//----------程序局部变量分配的空间地址---------------
cout<<"local pointer(pLocalString1): 0x"<<&pLocalString1<<endl; // 0x0012FF7C
cout<<"local pointer(pLocalString2): 0x"<<&pLocalString2<<endl; // 0x0012FF78
cout<<"local interger: 0x"<<&nLocal<<endl; // 0x0012FF74
cout<<"local const interger: 0x"<<&nLocalConst<<endl; // 0x0012FF70
cout<<"local pointer(pNew): 0x"<<&pNew<<endl; // 0x0012FF6C
cout<<"local pointer(pMalloc): 0x"<<&pMalloc<<endl; // 0x0012FF68
cout<<"local const interger2: 0x"<<&nLocalConst2<<endl; // 0x0012FF64
delete pNew;
delete pMalloc;
return 0;
}
内存对齐方式虽然浪费一些内存,但由于CPU在对齐方式下运行比较快,所以一般对程序性能还是有好处的。
C/C++程序中的struct、class和class在编译时也会对成员变量进行对齐处理。开发人员可以通过
#pragma pack()或者编译器的编译选项来控制对struct、union和class的成员变量按多少字节对齐,或者
关闭对齐。