Is it safe to delete a NULL pointer?
And is it a good coding style?
Is it safe to delete a NULL pointer?
And is it a good coding style?
delete
performs the check anyway, so checking it on your side adds overhead and looks uglier. A very good practice is setting the pointer to NULL after delete
(helps avoiding double deletion and other similar memory corruption problems).
I'd also love if delete
by default was setting the parameter to NULL like in
#define my_delete(x) {delete x; x = NULL;}
(I know about R and L values, but wouldn't it be nice?)
new
suboject ! It's not exception-safe to delete
the old object first - you could end up with no subobject at all. Therefore, you wouldn't set the pointer to NULL; you'd set it to the new object. –
Beaverbrook (T*)1
instead of nullptr
will do that, it will crash hard if you try to delete it again. –
Teirtza NULL
being legal and setting invalid pointers to that value hides this problem. It makes programs that don't get ownership right "well behaving". –
Teirtza <template T> void my_delete(T*& p) { delete p; p = NULL; }
–
Luminal my_delete(Order3PizzasAndBurnTheBakery())
–
Dumps int** foo(void){static int *arr = new int(4); return &arr;}
calling my_delete(*foo())
will allocate, delete, then allocate again and finally nullify arr
(no pointers to allocated memory - memory leak). On the other hand my_delete(x) {auto _tmp = &(x); ..
will fail if x
is direct function call (not an lvalue). I wonder why such error-prone code is in accepted answer. –
Premillennialism From the C++0x draft Standard.
$5.3.5/2 - "[...]In either alternative, the value of the operand of delete may be a null pointer value.[...'"
Of course, no one would ever do 'delete' of a pointer with NULL value, but it is safe to do. Ideally one should not have code that does deletion of a NULL pointer. But it is sometimes useful when deletion of pointers (e.g. in a container) happens in a loop. Since delete of a NULL pointer value is safe, one can really write the deletion logic without explicit checks for NULL operand to delete.
As an aside, C Standard $7.20.3.2 also says that 'free' on a NULL pointer does no action.
The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.
NULL
is a perfectly reasonable thing to do in at least one case: when NULL
indicates a resource was never allocated in the first place (but could have been) and where external constraints (e.g. the need to let a C API own the resource) prevent using RAII. –
Aileen Yes it is safe.
There's no harm in deleting a null pointer; it often reduces the number of tests at the tail of a function if the unallocated pointers are initialized to zero and then simply deleted.
Since the previous sentence has caused confusion, an example — which isn't exception safe — of what is being described:
void somefunc(void)
{
SomeType *pst = 0;
AnotherType *pat = 0;
…
pst = new SomeType;
…
if (…)
{
pat = new AnotherType[10];
…
}
if (…)
{
…code using pat sometimes…
}
delete[] pat;
delete pst;
}
There are all sorts of nits that can be picked with the sample code, but the concept is (I hope) clear. The pointer variables are initialized to zero so that the delete
operations at the end of the function do not need to test whether they're non-null in the source code; the library code performs that check anyway.
void func(void) { X *x1 = 0; Y *y1 = 0; … x1 = new[10] X; … y1 = new[10] Y; … delete[] y1; delete[] x1; }
. I've not shown any block structure or jumps, but the delete[]
operations at the end are safe because of the initializations at the start. If something jumped to the end after x1
was allocated and before y1
was allocated and there was no initialization of y1
, then there'd be undefined behaviour — and while the code could test for nullness (of x1
and y1
) before the deletions, there is no need to do so. –
Analyzer Deleting a null pointer has no effect. It's not good coding style necessarily because it's not needed, but it's not bad either.
If you are searching for good coding practices consider using smart pointers instead so then you don't need to delete
at all.
To complement ruslik's answer, in C++14 you can use this construction:
delete std::exchange(heapObject, nullptr);
It is safe unless you overloaded the delete operator. if you overloaded the delete operator and not handling null condition then it is not safe at all.
There is a FAQ on this matter which answers this question.
The C++ language guarantees that delete p will do nothing if p is null. Since you might get the test backwards, and since most testing methodologies force you to explicitly test every branch point, you should not put in the redundant if test.
It is safe and better practice to directly call delete without checking if it is null.
I have experienced that it is not safe (VS2010) to delete[] NULL (i.e. array syntax). I'm not sure whether this is according to the C++ standard.
It is safe to delete NULL (scalar syntax).
delete[] NULL
. –
Edson null
: i.stack.imgur.com/Ug327.png –
Gereron © 2022 - 2024 — McMap. All rights reserved.
delete
. Use RAII instead. That is, usestd::vector<T> v(100);
instead ofT* p = new T[100];
, use smart pointers likeunique_ptr<T>
andshared_ptr<T>
that take care of deletion instead of raw pointers etc. – Isopropylmake_shared
(c++11) andmake_unique
(c++14) your program should contain zero ofnew
anddelete
– Knobnew
ordelete
. Classes designed to manage resources, where Standard components can't do the job, can of course do what they need to do, but the point is that they do the ugly stuff with the memory they manage, not the end-user code. So, make your own library/helper class to donew
/delete
, and use that class instead of them. – Housekeeping