Search code examples
cwindowspointerswinapi

How to check if a pointer is valid?


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?


Solution

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