What you don't know -- it is best to assign a NULL value after the delete pointer in C ++

Source: Internet
Author: User

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.

 

Related Article

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.