Removing a null pointer

Possible duplicate:
Is there any reason to check for a NULL pointer before deleting?

I often see the following in code:

if(pointer) delete pointer; 

As far as I understand, it is safe to delete a null pointer, so what is the point of this check?

+6
source share
4 answers

delete checks to see if the NULL pointer is for you, so you are correct that no check is required.

You can also see that some people set the pointer to NULL after deleting it, so you don’t do anything stupid like try and use memory that is no longer yours or does not allow you to delete the pointer twice, which will lead to an error.

+9
source

While this is safe, this has not always been :-), so this is probably familiar. There are also other consequences to removal. 1) if you use a specialized memory manager and redefine new ones and delete operators, then you may very well need to check the “Delete operator” for more information. more details

+1
source

Verification is not required.

The documentation states that the deletion will "free up the memory block pointed to by ptr (if not-null)"

+1
source

Most people do this because they usually have error handling otherwise (besides this I really don't see the point of doing a check). In some cases, they do this to verify that they are freeing something, and not accidentally changing the pointer somewhere and causing a memory leak without freeing it. free(NULL); should work in all cases, and not with an error, therefore, if there is no error handling in it, you can delete the if statement and just make it free.

0
source

Source: https://habr.com/ru/post/900753/


All Articles