内存分区模型
不同区域存放的数据 赋予不同的生命周期 给我们更大的灵活编程
程序运行前只有代码区以及全局区
代码区
存放函数体的二进制代码(cpu执行的机器指令) 由操作系统进行管理的
1.共享:对于频繁被执行的程序只需要在内存中有一份代码
2.只读:防止程序以外修改它的指令
全局区
存放 全局变量 静态变量(static修饰) 字符串常量 全局常量(const修饰的全局变量)
全局区不包括const修饰的局部变量
程序结束后由操作系统释放
程序运行后
栈区
编译器自动分配释放 存放函数参数值 局部变量 形参数据
不要返回局部变量的地址
[] [c++]1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| #include<bits/stdc++.h> using namespace std;
int * func() { int a=10;//局部变量存放在栈区 栈区数据在函数执行完后自动释放 return &a; //返回局部变量的地址 }
int main() { int *p=func(); cout<<*p<<endl;//第一次正确 因为编译器做了保留 cout<<*p<<endl;//乱码 system("pause"); }
|
堆区 程序员分配 释放 若不释放则程序结束时由操作系统回收
c++中主要利用new在堆区开辟
[] [c++]1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include<bits/stdc++.h> using namespace std;
int * func() { //利用new关键字可以将数据开辟到堆区 返回地址 //指针的本质也是局部变量 此处其保存的地址放在栈上 指针保存的地址指向的数据是放在堆区 int*p=new int(10); //new返回的是该数据类型的指针(地址) return p; }
int main() { int *p=func(); cout<<*p<<endl; cout<<*p<<endl; system("pause"); }
|
进阶基础操作
手动释放用delete
[] [c++]1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include<bits/stdc++.h> using namespace std;
int * func() { //在堆区创建整型数据 //new返回的是该数据类型的指针 int *arr=new int[10]; for(int i=0;i<100;i++) { arr[i]=i+100; } delete[] arr; //删除数组需要加中括号
}
void test01() { int *p=func(); cout<<*p<<endl; cout<<*p<<endl; cout<<*p<<endl; delete p; cout<<*p<<endl;//此时被释放了 乱码 } void test02() { //创建10整型数据的数组在堆区 new int [10];//10代表十个元素 }
int main() { func(); test01(); }
|