Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting pointer to NULL before delete

Tags:

c++

pointers

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;
}
like image 659
audiFanatic Avatar asked Feb 12 '16 20:02

audiFanatic


People also ask

Should pointer be set to null after delete?

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.

Do I need to check for null before delete p?

[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.

Can you set a pointer to null?

We can directly assign the pointer variable to 0 to make it null pointer.

What happens when you set a pointer to null?

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.


1 Answers

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
like image 86
pyj Avatar answered Oct 14 '22 15:10

pyj