如何识别野指针 [英] How to recognize a wild pointer

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

问题描述

如何识别通配指针?

推荐答案

最好的办法是首先防止/避免使用它们.

据我所知,没有一种标准的,实现独立的方法来区分一个统一的指针和一个通过检查指针值来指向分配的内存的指针.据我了解,在某些环境中检查未初始化指针的值可能会触发陷阱并暂停程序.

答案是没有未初始化的指针.

我的建议是使用智能指针和RAII习惯用法.我个人倾向于根据情况选择boost :: scoped_ptr和shared_ptr(来自boost还是std :: tr1).

如果坚持使用原始指针,则每当定义一个原始指针时,如果不立即将其设置为某个有效地址,请将其初始化为NULL.同样,将其删除后,立即将其设置为NULL.那么它要么为NULL,要么指向某物.但是,请记得在90年代,C ++中已添加了例外.为了使用这种方法使代码正确,考虑到了潜在的异常情况,可能需要创建无法维护的try-catch块的嵌套.我建议重新考虑采用智能指针/RAII方法.
The best thing is to prevent/avoid them in the first place.

As far as I know, there is no standard, implementation independant way to distinguish between an unitialized pointer and one that is pointing to allocated memory by examining the pointer value. As I understand it, examining the value of an uninitialized pointer in some environments could trigger a trap and halt your program.

The answer is not to have uninitialized pointers.

My recommendation is to use smart pointers and the RAII idiom. I personally tend to favor boost::scoped_ptr and shared_ptr (either from boost or std::tr1) depending on the situation.

If you insist on using raw pointers, whenever you define one, if you are not immediately setting it to some valid address, initialize it to NULL. Also immediately when you delete it, set it to NULL. Then it is either NULL or pointing to something. However, do recall that exceptions were added to C++ back in the 90''s. To get your code correct with this approach accounting for the potential of exceptions could require creating a rat''s nest of unmaintainable try-catch blocks. I''d suggest reconsidering adopting the smart pointer/RAII approach.


尚未初始化的本地指针将包含随机数据,因此您不能依靠内容来确定是否已分配它们.如果这是您关心的事情,那么在创建它们时应始终将其初始化为NULL.
Local pointers that have not been initialised will contain random data so you cannot rely on the contents to determine whether they have been allocated. If this is something you care about then you should always initialise to NULL when you create them.


它将剪短头发,并可能会咬住您.

你到底在说什么 ?您的意思是指针泄漏了内存吗?根据定义,那是您无法处理的.
It will have a shaggy hair cut, and might try to bite you.

What on earth are you talking about ? Do you mean a pointer that has leaked memory ? By definition, that''s one you have no handle to anymore.


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

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