memory in a C + + program is divided into two parts :
A. Stack: All variables declared inside the function will occupy the stack memory.
B. Heap: This is unused memory in the program that can be used to dynamically allocate memory while the program is running.
1.new operator
Allocates memory in the heap at run time for a variable of the given type, returning the allocated space address.
Check to see if the new operator returns a NULL pointer and take the following appropriate action:
Double* pvalue = NULL; if ( ! (Pvalue New Double ) { "error:out of memory. " <<Endl; Exit (1); }
Attention:
About the malloc () function: the malloc () function appears in C, and it still does exist, but it is recommended that you try not to use the malloc () function.
New not only allocates memory, it also creates objects.
2.delete operator
Release the memory it occupies
#include <iostream>using namespacestd;intMain () {Double* pvalue = NULL;//null-initialized pointerPvalue =New Double;//request memory for a variable*pvalue =29494.99;//Store the value at the assigned addresscout <<"Value of Pvalue:"<< *pvalue <<Endl; DeletePvalue//Freeing Memory return 0;}
3. Dynamic memory allocation for arrays
A. One-dimensional arrays
Char* pvalue = NULL; // null-initialized pointer pvalue newchar[// request memory for variable // int *array=newint//Delete [] array;
B. Two-dimensional arrays ( especially note that two-dimensional arrays need to be deleted by dimension )
int**Array//assuming that the first dimension of the array is M and the second dimension is n//Dynamically allocating spaceArray =New int*[m]; for(intI=0; i<m; i++) {Array[i]=New int[n];}//Release for(intI=0; i<m; i++ ){ Delete[] arrar[i];}Delete[] array;
C. Three-dimensional array (same two-dimensional)
int***Array;//assuming that the first dimension of the array is M, the second dimension is N, and the third dimension is H//Dynamically allocating spaceArray =New int**[m]; for(intI=0; i<m; i++) {Array[i]=New int*[n]; for(intj=0; j<n; J + +) {Array[i][j]=New int[H]; }}//Release for(intI=0; i<m; i++ ){ for(intj=0; j<n; J + + ) { DeleteArray[i][j]; } Deletearray[i];}Delete[] array;
D. Object memory allocation
The distribution is the same, but you need to be careful when deleting.
Delete ptr//Delete[] RG//is used to release the memory pointed to by RG, and one by one calls the destructor!! of each object in the array
Int/char/long/int*/struct and so on simple data type, because the object is not destructor, so with delete and delete [] is the same!
C + + dynamic memory