The role of pointer delete, the role of pointer delete

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.