1.内存分区模型
(1)代码区:存放函数体的二进制代码,由操作系统进行管理
代码区是共享的,共享的目的是对于频繁被执行的程序,只需要在内存中有一份即可,代码区是只读的。
(2)全局区:存放全局变量静态变量以及常量
这个区域的数据在程序介绍后被系统释放
#include <iostream>
using namespace std;
int g_a = 10;
int g_b = 20;
const int g_c = 30;
const char g_arr[] = "asdj12";
int main()
{
//全局区
//全局变量、静态变量、常量
static int c = 30;
const int d = 11;
const char arr[] = "linux";
//局部变量
int a = 10;
int b = 20;
cout << "局部变量a的地址" << (int)&a << endl; //栈区
cout << "局部变量b的地址" << (int)&b << endl; //栈区
cout << "全局变量g_a的地址" << (int)&g_a << endl; //全局区
cout << "全局变量g_b的地址" << (int)&g_b << endl; //全局区
cout << "const修饰的全局变量g_c的地址" << (int)&g_c << endl; //全局区
cout << "静态局部变量c的地址" << (int)&c << endl; //全局区
cout << "字符串常量的地址" << (int)&"asdafqqw" << endl; //全局区
cout << "const修饰的局部字符变量arr的地址" << (int)arr << endl; //栈区
cout << "const修饰的全局字符变量g_arr的地址" << (int)g_arr << endl; //全局区
cout << "const修饰的局部变量d的地址" << (int)&d << endl; //栈区
system("pause");
return 0;
}
通过观察地址判断在哪个区
(3)栈区:由编译器自动分配释放,存放函数的参数值局部变量等
#include <iostream>
using namespace std;
int *func1()
{
int a = 10;
return &a;
}
int func2()
{
int a = 10;
return a;
}
int main()
{
int ret = func2();
int *p = func1();
//int ret = func2();
cout << ret << endl; //10
//cout << ret << endl; //10
cout << *p << endl; //不调用func2先调用或不调用时为10,这种情况如果运用了上面两句代码也为不确定数
//后调用func2后为不确定数,在这个局部变量数据生命周期结束后原本的内存被别人占用
cout << *p << endl; //不确定数
cout << p << endl; //地址不变
cout << p << endl;
system("pause");
return 0;
}
(4)由程序员分配和释放,若程序员不释放则由操作系统回收
#include <iostream>
using namespace std;
int *func1()
{
//利用new关键字可以将数据开辟到堆区
int *p = new int(10);
return p;
}
int main()
{
int *p = func1();
cout << *p << endl; //10
cout << *p << endl; //10
system("pause");
return 0;
}
(4)释放堆内存
#include <iostream>
using namespace std;
//new的基本语法
int *func1()
{
//在堆区创建整形数据
//new返回的是该数据类型的指针
int *p = new int(10);
return p;
}
void test01()
{
int *p = func1();
cout << *p << endl;
cout << *p << endl;
//如果想释放开辟的堆区的数据,利用关键字delete
delete p;
//cout << *p << endl; //非法操作
}
void test02()
{
//创建10整形数据的数组,在堆区
int * arr = new int[10]; //代表数组有10个元素
for (int i = 0; i < 10; i++)
{
arr[i] = i+100; //给10个元素赋值100-109
}
for (int i = 0; i < 10; i++)
{
cout << arr[i] << endl;
}
delete[] arr; //释放堆区数组
}
int main()
{
test01();
test02();
system("pause");
return 0;
}
2.分区的意义
不同的区域存存放的数据,赋予不同的生命周期,给我们更大的灵活编程。