内存分为四个区域:代码区、全局区、栈区、堆区
1.1 程序运行前
代码区是共享的、只读的,存放CPU的机器指令
全局区存放全局变量和静态变量以及常量(字符串常量、全局常量),该区域的数据在程序结束后由操作系统释放
1.2 程序运行后
栈区:由编译器自动分配释放,存放函数的参数值(形参),局部变量等
不要返回局部变量的地址
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| #include <iostream> using namespace std; int* func() { int a = 20; return &a; } int main() { int* p = func(); cout << *p << endl; cout << *p << endl; }
|
堆区:由程序员分配释放,若程序员不是放,程序结束时由操作系统回收
在cpp中主要利用new在堆区开辟内存
1.3 new关键字
堆区开辟的数据,由程序员手动删除,利用操作符delete
利用new创建的数据,会返回数据对应的类型的指针
利用new在堆区创建数组
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
| #include <iostream> using namespace std; int* func() { int *p = new int(10); return p; } void test01() { int* p = func(); cout << *p << endl; cout << *p << endl; 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; } int main() { test01(); test02(); }
|