tags:

views:

718

answers:

3

I'm working with C++ unmanaged, the problem that I have happens when I call a method that returns an LPVOID.

LPVOID MyMethod(...);

The problem is that this method sometimes returns a Bad Ptr and I want to know if there is a way of detecting this, if the value returned is a Bad Ptr.

I have tried asking if it is NULL with no luck.

The only way in which I realize if the result is a Bad Ptr is while I'm debugging, I have tried some different ways but still unable to do it.

+10  A: 

No, there is no easy way to determine if a pointer is bad.

Windows does have IsBadReadPtr, IsBadWritePtr. These functions are inherently flawed - they only determine if a function is readable or writable in your address space at the moment of the call. They can also be the cause of security issues and should never be used.

The main issue is that there is no way to differentiate between a "bad" pointer that is still accessible to your process, and a good pointer.

For instance,

int g[5];
int somethingElse;

void* GetPointer()
{
   return &g[5]; // Whoops, off by one.
}

&g[5] is probably a valid pointer in your process, and might be pointing to somethingElse, you'll be able to access it without crashing but writing to it will corrupt your state.

Michael
See also Raymond Chen's http://blogs.msdn.com/oldnewthing/archive/2006/09/27/773741.aspx
Eclipse
+6  A: 

Your real problem is that you're calling a function that returns bad pointers. Do you have access to its source code? 90% of the time I've encountered problems like this, it's because either:

1) The function is returning a pointer to the stack; e.g.,

char a[10];
...
return a;

2) The function is returning a pointer that was never assigned valid memory to begin with:

char* foo; // Invalid pointer
 ...
return foo;

3) The function is returning a pointer that was already deleted (or free'd):

char* foo = new char[10];
...
delete[] foo;
return foo;

You really need to find the real problem, rather than work around it.

Dan Breslau
+1  A: 

LPVOID is a typedef to a pointer to void, Visual studio typically displays NULL values as "bad pointer" in the watch pane, are you sure that this pointer is not NULL?

Motti
NULL shows up as NULL on my machine, and <Bad Ptr> shows up when something is really FUBARed and there is no way the held address could be valid.
crashmstr