tags:

views:

2561

answers:

5

My current code to the effect of:

if( objectPointer != NULL){
    delete objectPointer;
}

doesn't work because the pointers are getting set to invalid hex numbers by the compiler such as:

  • 0xbaadf00d
  • 0xdeadbeef

etc....

So what's the best way to check for an invalid pointer before trying to delete the object?

+8  A: 

The best way is setting it to NULL if it doesn't point to anything. Globals, pointers in other namespaces, and local static pointers are automatically initialized to be null pointers. Class members and normal locals should be initialized to NULL manually if you need to test them against NULL (some people like to use 0 instead. Of course, that's fully equivalent).

Then, you can check against NULL, but also can pass the pointer right away to delete, because it won't have any effect to delete a null-pointer (guaranteed by the C++ Standard).

Johannes Schaub - litb
+14  A: 

Always initialize your pointers to NULL (that is, 0). From http://www.lysator.liu.se/c/c-faq/c-1.html:

A null pointer is conceptually different from an uninitialized pointer. A null pointer is known not to point to any object; an uninitialized pointer might point anywhere.

Brett Daniel
+3  A: 

You're asking the wrong question.
Your pointers should never be getting these values in the first place. you can't rely on the compiler to set an invalid pointer to something. you always need to do it yourself by assigning a NULL to it.

shoosh
A: 

found this after I had posted as well.

DShook
+8  A: 

You don't need to check for not-NULL when calling delete. It is explicitly defined to do nothing.

delete NULL; // this is allowed

Any correct code you are writing would not be affected by these weird values the compiler is putting into your uninitialised or already freed memory. It puts those values there in order to help you find bugs. Ergo, you have a bug.

1800 INFORMATION