In a C/C ++ program, if the heap memory management mechanism is used, how is the memory allocated and recycled?
First look at a program:
# Include <iostream> using namespace std; int main (void) {int * x = new int; int * y = new int; * x = 1; * y = 2; cout <"* x =" <* x <endl; cout <"x =" <x <endl; delete x; int * z = new int; * z = 3; cout <"* z =" <* z <endl; cout <"z =" <z <endl; * x = 5; cout <"* z =" <* z <endl; return 0 ;}
This is because the program uses the heap memory management mechanism and there is a problem of memory reuse. The whole process is: when the program releases the memory of x, and then allocates the memory of z, this is the problem, because z occupies the memory of x, this means that the address of x and z is the same now !!! This is a terrible bug, because a pointer x, which is supposed to be invalid, can now change the content pointed to by the valid pointer z !! What should we do? In fact, we can clear the pointer every time we release the heap memory space pointed to by a pointer, that is, we need to add this code after delete:
X = NULL; or x = 0;
Although clearing a pointer may cause a program to crash, we would rather crash the program than make it extremely difficult to debug, because when the program crashes, we can observe to find the problem, however, it is difficult to find out the problem of a program like above !!!