如何检查指针是否有效? [英] How to check if a pointer is valid?

查看:46
本文介绍了如何检查指针是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很清楚这个问题的丑陋,我还是想知道是否有可能:

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 是个坏主意.

这篇关于如何检查指针是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆