内存分区模型
C++在执行程序时,将内存大方向分成4个区
- 代码区 存放二进制代码
- 全局区 存放全局变量和静态变量以及常量(常量:字符串,const修饰的全局变量)
- 栈区 由编译器自动分配释放,存放函数的参数值和局部变量
- 堆区 由程序员分配和释放,若程序员不释放,程序结束时由系统释放回收内存
全局区
#include <iostream>
using namespace std;
//全局变量
int g_a = 10;
int g_b = 20;
//全局常量, const修饰
const int c_g_a = 10;
const int c_g_b = 20;
int main()
{
//局部变量
int a = 10;
int b = 20;
cout << "局部变量a地址:" << &a << endl;
cout << "局部变量b地址:" << &b << endl;
//全局变量
cout << "全局变量g_a地址:" << &g_a << endl;
cout << "全局变量g_b地址:" << &g_b << endl;
//静态变量
static int s_a = 10;
static int s_b = 20;
cout << "静态变量s_a地址:" << &s_a << endl;
cout << "静态变量s_b地址:" << &s_b << endl;
//常量
//字符串常量
string str = "hello world"; //string str: 局部变量 "hello world":是常量
cout << "常量-字符串常量 str地址:" << &("hello world") << endl;
//局部常量:用const修饰,地址在局部变量附近
const int c_a = 10;
const int c_b = 20;
cout << "const修饰的局部变量c_a地址:" << &c_a << endl;
cout << "const修饰的局部变量c_b地址:" << &c_b << endl;
//地址在常量区域
cout << "const修饰的全局变量c_g_a地址:" << &c_g_a << endl;
cout << "const修饰的全局变量c_g_b地址:" << &c_g_b << endl;
}
堆区
由程序员分配释放,若程序员不释放,程序结束时由操作系统回收
在C++主要利用new 开辟堆区内存,delete释放堆区内存
#include <iostream>
using namespace std;
//利用new 开辟堆区内存
int* func() {
//利用new 开辟堆区内存
int* p = new int(10);
return p;
}
void test01() {
int* p = func();
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
cout << *p << endl;
//堆区的数据,由程序员管理开辟,程序员管理释放
//如果想要释放堆区的数据,利用关键字delete
delete p;
//cout << *p << endl; delete操作后,地址访问属于非法操作,会引起系统异常。引发了异常: 读取访问权限冲突
}
// 在堆区利用new开辟数组
void test02() {
//c++创建数组的方式。
//方法一
int tab[] = { 1,2,3 };
//方法二
int tab1[10];
//方法三
int tab2[10] = { 1,2,3 };
//数组名 = 数组的首地址
int* p = new int[10];
for (int i = 0; i < 10; i++) {
//通过下标访问
p[i] = i + 100;
//通过解引用,指针偏移
//*p = i + 100;
//p++;
}
for (int i = 0; i < 10; i++) {
//通过下标访问
cout << p[i] << endl;
}
//释放堆区数组内存
//释放数组,需要加[], 否则释放的只是数组的首个元素
delete[]p;
//cout << p[0] << endl; //非法访问
}
int main() {
//test01();
test02();
return 0;
}