内存主要分为四个区:
代码区:存放函数体的二进制代码,有操作系统进行管理
全局区:存放全局变量、静态变量以及常量。程序结束后,有操作系统释放。
栈区:由编译器自动分配释放,存放函数的参数值、局部变量
堆区:由程序员分配和释放,若程序员没有进行释放,则程序结束后由操作系统回收
学习内容: 1.程序运行前
程序运行前分为全局区和代码区。代码区的特点时共享和只读。
2.程序运行后程序运行后就存在栈区和堆区:
栈区:存放局部变量,并且在函数内不能返回局部变量的地址。这是因为局部变量在栈区,函数执行完毕后就会自动释放,不会进行保留。产生乱码。
#includeusing namespace std; int* func() { int a = 10; //局部变量在栈区 return &a; //返回了局部变量的地址,会发生错误!!!! } int main() { int* p = func(); cout << "a = " << *p << endl; cout << "*************" << endl; cout << "a = " << *p << endl; system("pause"); return 0; }
堆区:使用关键字new在堆区开辟内存,new开辟的变量是地址,要用指针来接收。由程序员手动开辟,手动释放,释放利用操作符delete。
手动开辟:int * p = new int(10);要用地址来接收开辟的地址;
手动释放:delete p;p代表地址
#include2.2 delete释放内存空间using namespace std; int* func() { int* p = new int(18); return p; } int main() { int* p; p = func(); cout << "p = " << *p << endl; cout << "*************" << endl; cout << "p = " << *p << endl; system("pause"); return 0; }
#include2.3 在堆区开辟数组并释放空间using namespace std; int* func() { int* p = new int(18); return p; } int main() { int* p; p = func(); cout << "p = " << *p << endl; cout << "*************" << endl; delete p; //cout << "p = " << *p << endl; system("pause"); return 0; }
#include3.总结using namespace std; void func() { int* arr = new int[10]; for (int i = 0; i < 10; i++) { arr[i] = i + 1; } for (int j = 0; j < 10; j++) { cout << arr[j] << "t"; } } int main() { func(); system("pause"); return 0; }
指针的本质是局部变量,存放在栈区;指针保存的数据存放在堆区。



