raffaello-camoriano / RBDemo

Reactive Behaviors Demo
1 stars 0 forks source link

Deleting a pointer does not require check against NULL #9

Closed pattacini closed 10 years ago

pattacini commented 10 years ago

Here: C++ standard states that you can delete a pointer without checking against the NULL constant: if it's NULL then the operation remains safe.

pattacini commented 10 years ago

You are closing here the module, so it doesn't matter where the pointer points to after deletion; however, if you delete a pointer and then you are still supposed to go on with your workflow, it's a good practice to equate that pointer to NULL after deletion, like that:

delete actionL;
actionL=NULL;

Can you figure out why?

raffaello-camoriano commented 10 years ago

Fixed, I didn't know that best practice.

I think that a joint use of the following practices prevents the program from indiscriminately reading/writing in the heap: 1) NULL check on a pointer before accessing the object for reading/writing 2) Set pointer to NULL after deletion of the pointed object

As an example, consider the unlucky case of a program writing to the allocated object after an unsafe deletion in the following way:

delete actionL;
if (actionL != NULL) actionL->pushAction("open_hand");

Which is a heap overflow.

pattacini commented 10 years ago

Yep, that's right the point, indeed. Anyway, putting a check against NULL everywhere in the code becomes quite cumbersome. Choose always a well balanced trade-off.