一、内存分区概述
C++ 程序在运行时,内容通常被分为五大区域,也可以简化理解为四个分区(代码、全局、堆、栈),但更严谨地说应理解为五个分区(代码、全局、常量、堆、栈):
1. 代码区 (Code/Text Segment)
-
存放程序的机器指令
-
通常是只读的,防止被编辑
2. 全局区(Global Area)
包含下列内容:
-
已初始化的全局/静态变量(Data段)
-
未初始化的全局/静态变量(BSS段)
-
全局常量、字符串常量(.rodata 常量区)
-
生命周期:从程序开始到结束
3. 堆区 (Heap)
-
使用
new
或malloc
动态分配 -
手动释放:
delete/free
-
生命周期由开发者管理
4. 栈区 (Stack)
-
用于局部变量、函数参数等
-
系统自动分配和释放
-
生命周期短暂,随函数调用进出
二、示例代码
以下代码打印了各类变量的内容地址,便于进行分区分析:
#include <iostream>
#include <cstdlib> // 对于 system() 函数
using namespace std;
//全局变量
int g_a = 10;
int g_b = 10;
//全局常量
const int c_g_a = 10;
const int c_g_b = 10;
//全局静态变量
static int s_g_a = 11;
static int s_g_b = 11;
int main()
{
//局部变量
int a = 10;
int b = 10;
//静态局部变量
static int s_l_a = 10;
static int s_l_b = 10;
//局部常量
const int c_l_a = 10;
const int c_l_b = 10;
//堆区内存
int* p_l_a = new int(100);
int* p_l_b = new int(100);
// 地址打印
cout << "局部变量a地址为: " << (int)&a << endl;
cout << "局部变量b地址为: " << (int)&b << endl << endl;
cout << "全局变量g_a地址为: " << (int)&g_a << endl;
cout << "全局变量g_b地址为: " << (int)&g_b << endl << endl;
cout << "局部静态变量s_l_a地址为: " << (int)&s_l_a << endl;
cout << "局部静态变量s_l_b地址为: " << (int)&s_l_b << endl << endl;
cout << "全局静态变量s_g_a地址为: " << (int)&s_g_a << endl;
cout << "全局静态变量s_g_b地址为: " << (int)&s_g_b << endl << endl;
cout << "全局常量c_g_a地址为: " << (int)&c_g_a << endl;
cout << "全局常量c_g_b地址为: " << (int)&c_g_b << endl << endl;
cout << "局部常量c_l_a地址为: " << (int)&c_l_a << endl;
cout << "局部常量c_l_b地址为: " << (int)&c_l_b << endl << endl;
cout << "字符串常量\"hello world\"地址为: " << (int)&"hello world" << endl;
cout << "字符串常量\"hello world1\"地址为: " << (int)&"hello world1" << endl << endl;
cout << "堆区内存p_l_a地址为: " << (int)p_l_a << endl;
cout << "堆区内存p_l_b地址为: " << (int)p_l_b << endl << endl;
cout << "局部指针变量p_l_a地址为: " << (int)&p_l_a << endl;
cout << "局部指针变量p_l_b地址为: " << (int)&p_l_b << endl << endl;
delete p_l_a;
delete p_l_b;
return 0;
}
三、分区解释
通过地址输出,可以观察到:
-
栈区(局部变量/const):地址一般较高,向下增长
-
堆区(new 分配):地址较低,向上增长
-
全局区(全局变量、静态变量):地址靠近、稳定
-
常量区(全局 const、字符串常量):地址接近、通常只读
视频链接:
关注微信公众号 程序员陈子青 解锁你的高薪offer之旅。