如何检查是否一个指针是有效的?

如何检查是否一个指针是有效的?

问题描述:

我深知这一问题的丑陋的,我还是想知道这是否是可能的:

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

当某个程序试图读/写无效的指针(NULL,未分配的块等),Windows崩溃与访问冲突异常的应用程序。

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?

如果您必须使用原始指针最好的办法是,以确保它是一个有效的指针或NULL。然后,你可以检查它是否有效的检查,如果它等于NULL。

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.

但是,为了回答你的问题,你可以捕捉这类事情结构异常处理(SEH)

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

话虽这么说, SEH是一个坏主意