Testing pointers for validity (C/C++)(有效性测试指针 (C/C++))
问题描述
有什么方法可以确定(当然是以编程方式)给定的指针是否有效"?检查 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++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:有效性测试指针 (C/C++)
基础教程推荐
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01