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:
etc....
So what's the best way to check for an invalid pointer before trying to delete the object?
An invalid pointer reference occurs when a pointer's value is referenced even though the pointer doesn't point to a valid block. One way to create this error is to say p=q;, when q is uninitialized. The pointer p will then become uninitialized as well, and any reference to *p is an invalid pointer reference.
You can usually check for NULL using ptr == 0, but there are corner cases where this can cause an issue. Perhaps more importantly, using NULL makes it obvious that you are working with pointers for other people reading your code.
"Invalid pointer operation" means you freed memory that didn't belong to you. One of these three things is the cause: Your program freed something that had already been freed once before.
A pointer value is valid in C++ if: it is a null pointer value, or. it points to an object, or. it points to p[1] where &p[0] points to an object (i.e., “one position past an object”).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With