测试指针的有效性(C / C ++) [英] Testing pointers for validity (C/C++)

查看:372
本文介绍了测试指针的有效性(C / C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法来确定(编程,当然)如果给定的指针是有效?检查NULL容易,但怎么样之类的东西0x00001234?当试图取消引用这种指针发生异常/崩溃。

一个跨平台的方法是preferred,但特定平台的(适用于Windows和Linux)也行。

更新澄清:
这个问题是不是与陈旧的/释放/未初始化的指针;相反,我实现一个指针需要从调用者(比如一个指向字符串的指针,文件句柄等)的API。主叫方可以发送(在目的或误)无效的值作为指针。我如何prevent崩溃?


解决方案

  

澄清更新:这个问题是不是与陈旧,释放或未初始化的指针;相反,我实现一个指针需要从调用者(比如一个指向字符串的指针,文件句柄等)的API。主叫方可以发送(在目的或误)无效的值作为指针。我如何prevent崩溃?


您不能作出这样的检查。我们根本没有办法,你可以检查指针是否为有效。你必须相信,当人们用一个函数,指针,这些人知道他们在做什么。如果他们通过您0x4211作为指针值,那么你必须相信它指向的地址0x4211。如果他们不小心撞上物体,那么即使你会用一些可怕的操作系统功能(IsValidPtr或其他),你仍然会陷入一个bug,而不是快速失败。

开始使用空指针信令这种事情,并告诉您图书馆的用户,如果他们倾向于小心通过无效指针他们不应该使用指针,认真:)

Is there any way to determine (programatically, of course) if a given pointer is "valid"? Checking for NULL is easy, but what about things like 0x00001234? When trying to dereference this kind of pointer an exception/crash occurs.

A cross-platform method is preferred, but platform-specific (for Windows and Linux) is also ok.

Update for clarification: The problem is not with stale/freed/uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash?

解决方案

Update for clarification: The problem is not with stale, freed or uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash?

You can't make that check. There is simply no way you can check whether a pointer is "valid". You have to trust that when people use a function that takes a pointer, those people know what they are doing. If they pass you 0x4211 as a pointer value, then you have to trust it points to address 0x4211. And if they "accidentally" hit an object, then even if you would use some scary operation system function (IsValidPtr or whatever), you would still slip into a bug and not fail fast.

Start using null pointers for signaling this kind of thing and tell the user of your library that they should not use pointers if they tend to accidentally pass invalid pointers, seriously :)

这篇关于测试指针的有效性(C / C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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