c++ - 为什么在我计算 NULL 指针时抛出异常(读取访问冲突)?

标签 c++ c++11

因为 NULL 指针将零分配给它的值。

  1. 当我尝试计算一个空指针时,它抛出一个异常,这是为什么?它不输出零。

  2. 零值有地址吗?

示例代码:

int main()
{
    int *q = NULL;
    cout << *q;
    return 0;
}

最佳答案

存储在指针中的值(即地址)可以处于四种状态之一:

  1. 它可以指向一个对象。
  2. 它可以指向刚好超过对象末尾的位置。
  3. 可以是空指针,表示不绑定(bind)任何对象。
  4. 可以无效;前三项以外的值均无效。

复制或以其他方式尝试访问无效指针的值是错误的。作为 当我们使用未初始化的变量时,编译器不太可能检测到此错误。访问无效指针的结果是未定义的。因此,我们必须 始终知道给定的指针是否有效。

Although pointers in cases 2 and 3 are valid, there are limits on what we can do with such pointers. Because these pointers do not point to any object, we may not use them to access the (supposed) object to which the pointer points. If we do attempt to access an object through such pointers, the behavior is undefined.

关于c++ - 为什么在我计算 NULL 指针时抛出异常(读取访问冲突)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58586119/

相关文章:

c++ - 没有初始值设定项或显式默认构造函数的空类是否可用作 constexpr 变量?

C++:如何使用 decltype 从迭代器获取类型

c++ - 可变模板化结构/boost::variant 是如何实现的

c++ - 为什么要在私有(private)继承下覆盖?

c++ - libxml2 xmlTextReaderRead 返回 -1

c++ - 为什么在此 C++ 程序中编译可变长度数组?

c++ - for 循环条件中常量的评估

c++ - 类中成员声明顺序如果相互依赖,最优解

c++ - std::tuple of std::shared_ptr of template parameter pack

c++ - 对象切片: Access dervied class methods from base class object