Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check for an invalid pointer?

Tags:

c++

pointers

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?

like image 242
DShook Avatar asked Jan 27 '09 04:01

DShook


People also ask

Which of is invalid for pointer?

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.

How do I check if a pointer is null?

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.

What does invalid pointer operation mean?

"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.

What is a valid pointer in C++?

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”).


2 Answers

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.

like image 158
Brett Daniel Avatar answered Sep 20 '22 14:09

Brett Daniel


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.

like image 45
1800 INFORMATION Avatar answered Sep 19 '22 14:09

1800 INFORMATION