简体   繁体   中英

How to validate LPVOID to <Bad Ptr>

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.

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.

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; eg,

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.

LPVOID是指向void的指针的typedef ,Visual Studio通常在监视窗格中将NULL值显示为“坏指针”,你确定这个指针不是NULL吗?

No, you cant.

However, if you can create an auxiliary data structure to store locations and ensure you remove them from that auxiliary data structure when they get deleted (maybe add it to the destructor) you can check whether the pointers are in that structure before de-referencing them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM