C++的内存分为5类
1、堆,2、栈,3、常量存储区,4、静态存储区,5代码区
1、堆与栈的区别
数据结构中的堆与栈
栈(stack):是一种连续储存的数据结构,具有先进后出的性质。通常的操作有入栈(圧栈)push、出栈pop和栈顶元素top。想要读取栈中的某个元素,就要将其之前的所有元素出栈才能完成。类比现实中的箱子一样。
堆:是一种非连续的树形储存数据结构,每个节点有一个值,整棵树是经过排序的。特点是根结点的值最小(或最大),且根结点的两个子树也是一个堆。常用来实现优先队列,存取随意。
内存中的堆与栈
栈内存:由程序自动向操作系统申请分配以及回收,速度快,使用方便,但程序员无法控制。若分配失败,则提示栈溢出错误。注意,const局部变量也储存在栈区内,栈区向地址减小的方向增长。
堆内存:程序员向操作系统申请一块内存,当系统收到程序的申请时,会遍历一个记录空闲内存地址的链表,寻找第一个空间大于所申请空间的堆结点,然后将该结点从空闲结点链表中删除,并将该结点的空间分配给程序。分配的速度较慢,地址不连续,容易碎片化。此外,由程序员申请,同时也必须由程序员负责销毁,否则则导致内存泄露。
2、堆中存放的数据
堆,编译器不用去管,程序员使用new和malloc来申请内存,但必须在不使用的时候使用delete和free释放掉。
3、栈中存放的数据
栈中存放着局部变量,局部常量,函数参数。
4、常量存储区
常量存储区内存放:全局常量,函数指针,常量数组,对函数指针
5、静态存储区
全局变量、全局静态变量,局部静态变量,以及虚函数表
6、代码区
存放代码
#include <bits/stdc++.h>
using namespace std;
int c=1;
static int q=1;
const int cg=1;
class QIAO
{
public:
int name;
QIAO(int a)
{
name=a;
}
};
void test()
{
const int b = 2;
printf("the location of the const variable in function: %p\n",&b);
int a=1;
printf("the location of the variable in function: %p\n",&a);
}
int main()
{
static int w=1;
//静态存储区
cout<<"static storage area : "<<&c<<endl;
cout<<"static storage area : "<<&q<<endl;
cout<<"static storage area : "<<&w<<endl;
//下面是常量存储区
cout<<"const storage area: "<<&cg<<endl;
// cout<<"const storage area: "<<&test<<endl;
printf("const storage area: ",&test);
//下面是栈
QIAO *qiao = new QIAO(1);
vector<QIAO> ch(10,0);
cout<<"the location of new class : "<<&ch<<endl;
cout<<"the loaction of class vector "<<&qiao<<endl;
int a[10]={1};
cout<<"the loaction of int array in function "<<&a<<endl;
const int d=10;
printf("the location of the const variable in function: %p\n",&d);
test();
//堆
int* cd = new int(5);
int* ce = (int*)malloc(sizeof(int));
printf("The location of new point: %p\n",cd);
printf("The location of malloc point: %p\n",ce);
}
结果: