audiFanatic
audiFanatic

Reputation: 2504

Setting pointer to NULL before delete

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;
}

Upvotes: 8

Views: 4310

Answers (3)

i486
i486

Reputation: 6563

The author has wanted to write:

delete m_pio;
m_pio = NULL;

but messed the lines and there is bad bug. Assigning NULL after delete is good prectice to protect the variable from another delete.

Upvotes: 1

pyj
pyj

Reputation: 1499

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

Upvotes: 7

user2209008
user2209008

Reputation:

Obviously we can't discern what the original author had intended.

On a side note, you'd be surprised at the amount of people I've worked with (even industry veterans) who have it in their head that deleteing or freeing NULL is somehow a bad thing that needs to be guarded against, despite that there are no consequences for it. It just ends up creating a huge tidal wave of unnecessary checks, especially when the developer in question is especially fond of wasting their time manually managing memory.

Upvotes: 0

Related Questions