C/C++程序的内存分配与使用笔记

发表于:2014-8-22 10:14

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:tiany524    来源:51Testing软件测试网采编

  一、C/C++程序的内存分配
  一个C/C++程序占用的内存区一般可以分为如下五种:
  ①全局/静态数据区
  ②常量数据区
  ③代码区
  ④堆
  ⑤栈
  显然代码存放在代码区,而程序的数据则根据数据种类的不同放在不同的存储区中,在C/C++中,数据主要有几种不同的分类:常量和变量、全局数据和局部数据,静态数据与非静态数据,以及程序运行中产生和释放的动态数据。
  其中
  ①全局/静态数据区中存储全局变量及静态变量(包括全局静态变量和局部静态变量);
  ②常量数据区中存储程序中的各种常量;
  ③栈中存储自动变量后者局部变量,以及传递的函数参数等
  ④堆是用户控制的存储区,存储动态产生的数据(new或者malloc)。
  下面通过一个简单的实例来具体看看:
#include
#include
int g_nGlobal = 100;
int main()
{
char *pLocalString1 = "LocalString1";
const char *pLocalString2 = "LocalString2";
static int nLocalStatic = 0;
int nLocal = 0;
const int nLocalConst = 100;
int *pIntNew = new int[5];
char *pMalloc = (char *)malloc(1);
printf("global variable:                0x%x/n", &g_nGlobal);
printf("static variable:                0x%x/n", &nLocalStatic);
printf("local printer1:                 0x%x/n", pLocalString1);
printf("local const printer:            0x%x/n/n", pLocalString2);
printf("new:                            0x%x/n", pIntNew);
printf("malloc:                         0x%x/n/n", pMalloc);
printf("local printer(pIntNew):         0x%x/n", &pIntNew);
printf("local printer(pLocalString1):   0x%x/n", &pLocalString1);
printf("local printer(pLocalString2):   0x%x/n", &pLocalString2);
printf("local variable(nLocal):         0x%x/n", &nLocal);
printf("local printer(pMalloc):         0x%x/n", &pMalloc);
printf("local const(nLocalConst):     0x%x/n", &nLocalConst);
delete []pIntNew;
free(pMalloc);
return 0;
}
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号