程序运行前
代码区
- 存放函数体的二进制代码,由操作系统进行管理的
存放 CPU 执行的机器指令
代码区是共享的,共享的目的是对于频繁被执行的程序,只需要在内存中有一份代码即可
代码区是只读的,使其只读的原因是防止程序意外地修改了它的指令
全局区
- 存放全局变量和静态变量以及常量
全局变量和静态变量存放在此.
全局区还包含了常量区, 字符串常量和其他常量也存放在此.
该区域的数据在程序结束后由操作系统释放.
//全局变量
int g_a = 10;
int g_b = 10;
//全局常量
const int c_g_a = 10;
const int c_g_b = 10;
int main() {
//局部变量
int a = 10;
int b = 10;
//打印地址
cout << "局部变量a地址为: " << (int)&a << endl;
cout << "局部变量b地址为: " << (int)&b << endl;
cout << "全局变量g_a地址为: " << (int)&g_a << endl;
cout << "全局变量g_b地址为: " << (int)&g_b << endl;
//静态变量
static int s_a = 10;
static int s_b = 10;
cout << "静态变量s_a地址为: " << (int)&s_a << endl;
cout << "静态变量s_b地址为: " << (int)&s_b << endl;
//字符串常量
cout << "字符串常量地址为: " << (int)&"hello world" << endl;
cout << "字符串常量地址为: " << (int)&"hello world1" << endl;
//全局常量
cout << "全局常量c_g_a地址为: " << (int)&c_g_a << endl;
cout << "全局常量c_g_b地址为: " << (int)&c_g_b << endl;
//局部常量
const int c_l_a = 10;
const int c_l_b = 10;
cout << "局部常量c_l_a地址为: " << (int)&c_l_a << endl;
cout << "局部常量c_l_b地址为: " << (int)&c_l_b << endl;
system("pause");
return 0;
}
程序运行后
栈区
由编译器自动分配释放, 存放函数的参数值,局部变量等
int* func()
{
int a = 10;
return &a;
}
栈区数据编译器会自动释放,不要返回局部变量的地址
堆区
由程序员分配释放,若程序员不释放,程序结束时由操作系统回收
- new关键字
int* func()
{
//利用new关键字 -> 堆区
int* p = new int(10);
return p;
}
new 基本语法
#include <iostream>
using namespace std;
int* func()
{
//利用new关键字 -> 堆区
int* p = new int(10); //new返回一个地址
return p;
}
int main()
{
int* p1 = func();
cout << *p1 << endl;
delete p1; //释放
cout << *p1 << endl; //非法访问
return 0;
}
new开辟数组
void func2()
{
int* arr = new int[10];
for (int i = 0; i < 10; i++)
{
arr[i] = 100 + i;
cout << arr[i] << endl;
}
}
new不可以为对象设置初始值。
int* pa = new int[10](100); // error: array 'new' cannot have initialization arguments