So I stumbled upon this bit of code and while I've been coding in C/C++ for about 5 years now, I cannot fathom why anybody would want to do this. I understand why you'd want to set the pointer to NULL
after deallocating memory, but I certainly don't understand why someone would want to do the opposite (looks like a memory leak to me).
Second, I'm pretty sure it's not necessary to check if the pointer is NULL
before setting it to NULL and deleting it, as discussed here.
if( m_pio )
{
m_pio = NULL;
delete m_pio;
}
Setting pointers to NULL following delete is not universal good practice in C++. There are times when it is a good thing to do, and times when it is pointless and can hide errors. There are plenty of circumstances where it wouldn't help. But in my experience, it can't hurt.
[16.8] Do I need to check for NULL before delete p? No! The C++ language guarantees that delete p will do nothing if p is equal to NULL.
We can directly assign the pointer variable to 0 to make it null pointer.
Explanation: What happens here is that when a Null pointer is created, it points to null, without any doubt. But the variable of Null pointer takes some memory. Hence when a pointer to a null pointer is created, it points to an actual memory space, which in turn points to null.
Double deleting an object can result in the destructor being called twice, so some people favor setting it to NULL
after deletion. This prevents the destructor from being called on memory which could have been reallocated from the pointer's previous memory address.
As shown here though, setting to NULL
before deleting is a memory leak. Fixed code without memory leak:
if( m_pio ) {
delete m_pio;
m_pio = NULL;
}
Note that calling delete on NULL
(or nullptr
in C++11), is legal so you code could just be written as this instead:
delete m_pio;
m_pio = NULL
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