Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it recommended to set a pointer to null after deleting it? [duplicate]

Tags:

c++

pointers

int* ptr = new int();
delete ptr; 
ptr = 0; // or null

My book is telling me that it is good practice to set a pointer to null or 0 after deleting what it points to. I'm not understanding why. Could someone give me a scenario in which this could cause a problem?

like image 780
Sam D20 Avatar asked Dec 18 '25 19:12

Sam D20


2 Answers

Just so that you know the pointer does not point to anything anymore, and will fail if conditions and other boolean checks:

   delete ptr;
   ptr = NULL;
   if(ptr)
     *ptr = 2;

This code will run perfectly fine, although it would cause memory corruption if the pointer was not set to NULL.

like image 155
RandyGaul Avatar answered Dec 20 '25 11:12

RandyGaul


That way, if you accidentally use ptr again later in your program, it causes a crash immediately rather than causing a hard-to-find bug later in the program.

like image 42
Joel Avatar answered Dec 20 '25 09:12

Joel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!