问题描述
有什么方法可以确定(当然是以编程方式)给定的指针是否有效"?检查 NULL 很容易,但是像 0x00001234 这样的东西呢?尝试取消引用此类指针时会发生异常/崩溃.
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.
首选跨平台方法,但特定于平台的方法(适用于 Windows 和 Linux)也可以.
A cross-platform method is preferred, but platform-specific (for Windows and Linux) is also ok.
更新说明:问题不在于陈旧/释放/未初始化的指针;相反,我正在实现一个 API,它从调用者那里获取指针(如指向字符串的指针、文件句柄等).调用者可以(有意或错误地)发送无效值作为指针.如何防止崩溃?
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?
推荐答案
澄清更新:问题不在于陈旧、释放或未初始化的指针;相反,我正在实现一个 API,它从调用者那里获取指针(如指向字符串的指针、文件句柄等).调用者可以(有意或错误地)发送无效值作为指针.如何防止崩溃?
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?
你不能做那个检查.您根本无法检查指针是否有效".您必须相信,当人们使用带指针的函数时,这些人知道他们在做什么.如果他们将 0x4211 作为指针值传递给您,那么您必须相信它指向地址 0x4211.而且如果他们不小心"撞到了一个对象,那么即使你使用了一些可怕的操作系统函数(IsValidPtr 或其他什么),你仍然会陷入一个错误并且不会很快失败.
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++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!