In C++, the memory is divided into 5 areas in detail
-
Stack
Function局部变量
storage area, automatically allocated and released by the system -
Heap
Programmers dynamically apply for memory,new
come out of memory, or come out of malloc. Use delete and free to release manually to prevent overflow -
Global/static storage area
Global variables and static static variable storage area -
Constant storage area
such as constant string, etc. "I am Chinese" -
Program code area
The area where the program is stored
C++ application for dynamic memory is new/delete, which is easier to use than C's malloc/free. It is essentially a method of calling C, but there are more initializations, etc.
-
new/delete
new not only allocates memory, but also does some initialization work, and delete also does some additional cleanup work.
For example, the pointer of a new class will call the constructor of this class to perform initialization work.int *p1 = new int //单个变量指针 int *p2 = new int(10); //顺带初始化了 int *p3 = new int[10] //申请一个数组,指针指向它 delete p1; delete p2; delete [] p3;
-
malloc/free
If the application fails, return NULL. Try not to use it when writing C++ programs, just use new/delete//很笨,只会申请一个大小为**的内存,返回是空指针,不知道指向谁,还要强制类型转换成(int*) int *p1 = (int*)malloc(sizeof(int)); int *p2 = (int*)malloc(10*sizeof(int)); //释放的时候倒是简单,不管数组还是单个变量,不用加[] //!!!!!!!注意是个free函数,不是 free p1; free(p1); free(p2);