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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With