Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete on already deleted object : behavior?

I am wondering what will hapen if I try to do a delete on a pointer that is already deleted, or may have not been allocated ? I've read two things : first, that delete operator will do some checkings and we do not need to check if the pointer is null ; and then, I read that it can lead to unknown behaviors..

I'm asking it, because I use some personal objects that contains Qt objects attributes ; I think that Qt delete all widgets associated when we close the window, but I'm not pretty sure and still : if the soft crash before the window's close, we have to delete all objects manually.

So, what would be the best solution ? Something like that ?

if( my_object )
    delete my_object;

Can it avoid dangerous behaviours ?

like image 344
Jérémy Dutheil Avatar asked Dec 14 '11 08:12

Jérémy Dutheil


4 Answers

delete on an already deleted non-null pointer is undefined behavior - your program will likely crash. You can safely use delete on a null pointer - it will yield a no-op.

So the real problem is not delete on a null pointer. The real problem is here:

 ptr = new Something();
 otherPtr = ptr;
 delete ptr;
 delete otherPtr;

This can happen if you have several pointers to the same object and it is quite dangerous. The possible solutions are:

  • use smart pointers (no delete in your code) or
  • only have one designated pointer for controlling each object lifetime and delete at exactly the right time.
like image 116
sharptooth Avatar answered Nov 17 '22 14:11

sharptooth


if( my_object )
    delete my_object;

is redundant. delete on a NULL pointer does nothing. This is guaranteed by the standard.

delete on a pointer that was already deleted causes undefined behavior. That's why you should always remember to assign your pointers to NULL after you delete them:

delete p;
p = NULL;

EDIT: As per the comments, I feel I should specify this. If you have multiple pointers to the same object, the assignment to NULL won't make the delete safe. Regardless, it's better to use smart pointers.

like image 43
Luchian Grigore Avatar answered Nov 17 '22 15:11

Luchian Grigore


Please note that deleting a pointer does not set it to NULL.

int* i = new int;
*i = 42;
delete i;
delete i; // oops! i is still pointing to the same memory, but it has been deleted already

Deleting a null pointer doesn't do anything, deleting an already deleted object will result in undefined behaviour.

like image 33
Jan Avatar answered Nov 17 '22 13:11

Jan


the right way is:

if( my_object )
{
    delete my_object;
    my_object = NULL;
}

because, calling twice the way it was before will call delete on a deleted pointer.

like image 1
Roee Gavirel Avatar answered Nov 17 '22 13:11

Roee Gavirel