What you don't know -- it is best to assign a NULL value after the delete pointer in C ++
We all know that in C ++, all pointer variables declared with new must be deleted. Unless you fully use smart pointers without worrying about memory leaks.
If you are from the C Sharp camp, you may be used to the benefits of hosting code and the garbage collection mechanism. However, in C ++, You need to manually release the instance and assign the instance to whom it is released.
First, I want to emphasize that delete is to release the memory pointed to by the pointer, rather than the memory occupied by the pointer. Taste this sentence slowly.
We try to write the following code:
# Include
Using namespace std; int main () {int * p = new int (10); delete p; return 0 ;}
There are no errors during compilation, but it will crash during running.
We tried to debug the program, but I was surprised that we could not set the delete statement to a breakpoint.
We try to modify the above Code: assign a null value to the pointer after the delete operation.
# Include
Using namespace std; int main () {int * p = new int (10); delete p; p = NULL; delete p; return 0 ;}
Compiled successfully and run successfully.
Therefore, to prevent the program from crashing because the same pointer is deleted twice, assign a NULL value to the pointer after the delete operation.
Remember:
C ++ ensures that deleting 0-value pointers is safe.