The role of pointer delete, the role of pointer delete
<span style="white-space:pre"></span>int i=1;int *p=new int;*p=i;cout<<&p<<endl<<p<<endl<<*p<<endl;delete p;cout<<&p<<endl<<p<<endl<<*p<<endl;
A small test was conducted, as shown in the code above.
The result is as follows:
After the delete pointer is displayed, if * p is used, it still has a value. To avoid errors, add: p = NULL after delete.
Delete
Delete only releases the memory indicated by the pointer, but does not kill the pointer itself.
Char * p = new char [100];
Strcpy (p, "hello ");
Delete p; // The Memory indicated by p is released, but the address indicated by p remains unchanged.
...
If (p! = NULL) // does not prevent errors
{
Strcpy (p, "world"); // Error
}
The tracing example with the debugger finds that the address of the pointer p remains unchanged (not NULL) after it is free, but the memory corresponding to the address is junk, and p becomes a "wild pointer ". If p is not set to NULL at this time, it is mistaken that p is a valid pointer.
If the program is long, we sometimes cannot remember whether the memory referred to by p has been released. Before using p, the statement if (p! = NULL. Unfortunately, the if statement does not prevent errors at this time, because even if p is not a NULL pointer, it does not point to a valid memory block.
Significance of setting 0 after the c ++ delete pointer
After the delete operation, the pointer points to an uncertain position, called the suspension pointer. If it is referenced by the pointer, the program will crash. Set 0 to make it a NULL pointer. Later programs can determine whether the pointer is NULL to determine whether it is valid.