Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to delete a NULL pointer?

Is it safe to delete a NULL pointer?

And is it a good coding style?

like image 482
qiuxiafei Avatar asked Nov 16 '10 02:11

qiuxiafei


People also ask

What happens if I delete null pointer?

What happens when delete is used for a NULL pointer? Explanation: Deleting a null pointer has no effect, so it is not necessary to check for a null pointer before calling delete.

Is it safe to free a null pointer?

It is safe to free a null pointer. The C Standard specifies that free(NULL) has no effect: The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation.

Do null pointers take up memory?

A NULL pointer doesn't allocate anything.

What is the problem with null pointer?

Because a null pointer does not point to a meaningful object, an attempt to dereference (i.e., access the data stored at that memory location) a null pointer usually (but not always) causes a run-time error or immediate program crash.


1 Answers

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?)

like image 178
ruslik Avatar answered Sep 19 '22 19:09

ruslik