tags:

views:

1237

answers:

7

I am well aware of the ugliness of this question, I'd still like to know if it's possible:

When a program tries to read/write to an invalid pointer (NULL, unallocated block, etc') windows crashes the application with an access violation exception.

The question is, is there a way to check wether this pointer will generate an exception before trying to use it, or else, is there a way to catch this exception?

+1  A: 

I don't know about Windows, but in *nix you could install a SIGSEGV signal handler to intercept the exception.

PaV
On Windows you can code a Structured Exception Handler to catch the exception.
ChrisW
Signal handling is not *nix-specific: it's part of the ISO-C standard library
Christoph
+1  A: 

IsBadReadPointer / IsBadWritePointer

RichieHindle
I know that there are IsBadRead/WritePtr, couldn't find Valid versions. However, MSDN says that they are obsolte
@Hammer: Sorry, I meant "Bad", now fixed. They're considered bad form because they're not threadsafe, but they the closest thing to what the OP is asking for.
RichieHindle
+6  A: 

There are functions IsBadReadPtr and IsBadWritePtr that might do what you want. There is also an article that explains why you shouldn't use them.

avakar
From MSDN:"Important: This function is obsolete and should not be used. Despite its name, it does not guarantee that the pointer is valid or that the memory pointed to is safe to use."
Hammer, yes, they are marked as obsolete and the article I linked to explains why. What are you trying to achieve, anyway?
avakar
A: 

I think you're looking for something like IsBadReadPtr.

Documentation:

http://msdn.microsoft.com/en-us/library/aa366713(VS.85).aspx

Suvesh Pratapa
+3  A: 

You can certainly test if the pointer is NULL!

if ( ptr == NULL ) {
   // don't use it
}

That is the only portable test you can do. Windows does provide various APIs to test pointers, but as others have pointed out, using them can be problematic.

anon
+5  A: 

Catching this kind of errors is addressing the symptoms, not the root cause.

The following idioms will work on any platform:

  • initialize all pointers to zero

  • if you cannot guarantee a pointer is valid, check that it is non-0 before indirecting it

  • when deleting objects, set the pointer to 0 after deletion

  • be careful of object ownership issues when passing pointers to other functions

laalto
+2  A: 

The best bet if you must use raw pointers is to make sure that it is either a valid pointer or NULL. Then you can check if it is valid by checking if it is equal to NULL.

But to answer your question, you can catch these kinds of things with structured exception handling (SEH).

That being said, SEH is a bad idea.

Brian R. Bondy