学习:内存分区模型

C++程序在执行时,将内存大方向划分为4个区域:

1、代码区:存放函数体的二进制代码,由操作系统进行管理的
2、全局区:存放全局变量和静态变量以及常量
3、栈区:由编译器自动分配释放, 存放函数的参数值,局部变量等
4、堆区:由程序员分配和释放,若程序员不释放,程序结束时由操作系统回收

#include<iostream>
#include<string>

using namespace std;

int g_a = 1;
int g_b = 1;
static int s_g_a = 1;
static int s_g_b = 1;
const int c_g_a = 1;
const int c_g_b = 1;

int main(){
    int l_a = 1;
    int l_b = 1;
    static int s_l_a = 1;
    static int s_l_b = 1;

    cout <<"全局变量g_a的内存地址:"<< &g_a << endl;
    cout <<"全局变量g_b的内存地址:"<< &g_b << endl;
    cout <<"全局const常量c_g_a的内存地址:"<< &c_g_a << endl;
    cout <<"全局const常量c_g_b的内存地址:"<< &c_g_b << endl;
    cout <<"静态局部变量s_l_a的内存地址:"<< &s_l_a << endl;
    cout <<"静态局部变量s_l_b的内存地址:"<< &s_l_b << endl;
    cout <<"静态全局变量s_g_a的内存地址:"<< &s_g_a << endl;
    cout <<"静态全局变量s_g_b的内存地址:"<< &s_g_b << endl;
    cout <<"局部变量l_a的内存地址:"<< &l_a << endl;
    cout <<"局部变量l_b的内存地址:"<< &l_b << endl;


    system("pause");
    return 0;

}

总结:
1、C++中在程序运行前分为全局区和代码区
2、代码区特点是共享和只读
3、全局区中存放全局变量、(静态/全局)静态变量、常量
4、常量区中存放 const修饰的全局常量 和 字符串常量
5、局部变量/常量存放在栈区,全局/静态变量存放在全局区,字符串常量和全局常量(就是被const修饰过的全局变量)存放在常量区


栈区:

特征:
1、由编译器自动分配释放, 存放函数的参数值,局部变量等
2、注意事项:不要返回局部变量的地址,栈区开辟的数据由编译器自动释放

#include<iostream>

using namespace std;

int * func() {
	int a = 10;
	return &a;
}

int main() {

	int * p = func();
	cout << *p << endl; //报错 因为当函数执行完栈区开辟的数据已经被自动释放了

	system("pause");
	return 0;
}

堆区:

由程序员分配释放,若程序员不释放,程序结束时由操作系统

在C++中主要利用new在堆区开辟内存

#include<iostream>

using namespace std;

int * func() {
	int * a = new int(10) //指针a 保存 int(10)在堆区的地址
	return a;  // 这里自己解释下,这时候返回a的地址 给main函数中的p指针,p指针接收到的其实是a中保存的int(10)的地址,而堆区的地址不会因为func结束而释放,并且return a比释放函数要早,所以p指针能够指向int(10)的地址
}

int main() {
	int * p = func();
	cout << *p << endl;

	
	system("pause");
	return 0;
}

总结:

1、堆区数据由程序员管理开辟和释放
2、堆区数据利用new关键字进行开辟内存


new操作符:

C++中利用new操作符在堆区开辟数据

语法: new 数据类型

利用new创建的数据,会返回该数据对应的类型的指针

int* func()
{
	int* a = new int(10);
	return a;
}

int main() {

	int *p = func();

	cout << *p << endl;
	cout << *p << endl;

	//利用delete释放堆区数据
	delete p;

	//cout << *p << endl; //报错,释放的空间不可访问

	system("pause");

	return 0;
}

使用delete操作符释放堆区开辟的内存,delete[] 操作符释放堆区开辟的数组连续的内存

#include<iostream>

using namespace std;

int * func01() {
	int * a = new int(10); //指针a 保存 int(10)在堆区的地址
	return a;
}


void test01() {
	int * p = func01();
	cout << *p << endl;
	delete p;

}

void test02() {
	int * arr = new int[10];
	for (int i = 0; i < 10; i++) {
		arr[i] = i + 100;
	}
	for (int i = 0; i < 10; i++) {
		cout << arr[i] << endl;
	}
	delete[] arr;
	//for (int i = 0; i < 10; i++) {
	//	cout << arr[i] << endl;
	//}

}

int main() {
	//int * p = func();
	//cout << *p << endl;
	//test01(); 单个值的堆区实现
	test02();//数组的堆区实现


	
	
	system("pause");
	return 0;
}
posted @ 2019-11-13 10:46  zpchcbd  阅读(215)  评论(0)    收藏  举报