Test if a pointer is still valid (C++)

Started by
8 comments, last by Qw3r7yU10p! 19 years, 2 months ago
I wonder, is there a way to test if a pointer is still pointing to a valid adress in memory, something like:

int* ptr1 = NULL;
int* ptr2 = NULL;

ptr1 = new int(5);
ptr2 = ptr1; // both pointer points to the same memory location

delete ptr2; // delete

// is there any function like this one???
if( test_pointer( ptr1 ) {
    *ptr1 = 6; 
}
Thanks in advance
My site Jvitel.com
Advertisement
You should always make the deleted pointer point to NULL (0). Then you can check it like this.

if(ptr != NULL)
..
there is but i'm not sure the exact functions.
also you could just do this:
bool testPointer (void* test) {   if (test)      return true;   return false;}//orif (test) { // where test is a pointer   return true;

Beginner in Game Development?  Read here. And read here.

 

If you are coding for Windows, then you can use IsBadReadPtr(); and IsBadWritePtr(); functions.

IsBadWritePtr

IsBadReadPtr

Hope this helps.
No, there's not. At least, not easily.

Look into boost's shared pointers. I've never used them, but I hear good things.

CM
None which isn't platform-specific.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

IsBadWritePtr

IsBadReadPtr

are ok but even Microsoft doesn't recomend them as they're not thread safe.

Gennerally this is done by wrapping a try/catch block around you trying to access the pointer. If an exception is thrown then its invalid.

However, the pointer could point ot valid memory but still be invalid for yoru purposes, which is another reason that the IsBadRad/WritePtr methods are basically worthless. Don't use them in any serious code.

Cheers
Chris
CheersChris
Alternatively, if you need to let everyone who has the pointer know that it is gone, you could use a double pointer.
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
Ok! got it, thanks for all your replies :-D I'll try to use smartpointers instead.
My site Jvitel.com
Quote:Original post by Pipo DeClown
You should always make the deleted pointer point to NULL (0). Then you can check it like this.

if(ptr != NULL)
..


I think you've missed the point. What if you have two pointers pointing to the same thing and you use one of them to delete it and set that pointer to null? The other pointer won't have a clue what has just happened.

This topic is closed to new replies.

Advertisement