如果没有发生左值到右值转换,是否取消引用无效指针是合法的 [英] Is dereferencing invalid pointers legal if no lvalue-to-rvalue conversion occurs

查看:96
本文介绍了如果没有发生左值到右值转换,是否取消引用无效指针是合法的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请尝试一下,我所看到的最接近的答案是

Try as I might, the closest answer I've seen is this, with two completely opposing answers(!)

问题很简单,这合法吗?

The question is simple, is this legal?

auto p = reinterpret_cast<int*>(0xbadface);
*p;  // legal?

我对此事

  1. 将整数投射到指针:对可以投射什么
  2. 间接:仅声明结果为左值.
  3. 生命周期:仅说明无法对对象执行的操作,有这里没有对象
  4. 表达式语句:*p是一个废弃的值表达式
  5. 舍弃的值表达式:不进行左值到右值转换
  6. >
  7. 左值的不确定性:也就是严格的别名规则,仅当左值将转换为右值
  1. Casting integer to pointer: no restrictions on what may be casted
  2. Indirection: only states the result is a lvalue.
  3. Lifetimes: only states what can't be done on objects, there is no object here
  4. Expression statements: *p is a discarded value expression
  5. Discarded value expressions: no lvalue-to-rvalue conversion occurs
  6. Undefined-ness of lvalues: aka strict aliasing rule, only if the lvalue is converted to a rvalue

因此,我得出结论,没有明确表示这是未定义的行为.但是我特别记得一些平台在间接指针上捕获了无效的指针.我的推理出了什么问题?

So I conclude there is nothing explicitly saying this is undefined behaviour. Yet I distinctively remember that some platforms trap on indirection for invalid pointers. What went wrong with my reasoning?

推荐答案

[basic.compound] 说:

指针类型的每个值都是以下之一:

Every value of pointer type is one of the following:

  • 指向对象或函数的指针(据说该指针指向该对象或函数),或者
  • 超出对象末尾的指针([expr.add]),或
  • 该类型的空指针值([conv.ptr]),或
  • 无效的指针值.
  • a pointer to an object or function (the pointer is said to point to the object or function), or
  • a pointer past the end of an object ([expr.add]), or
  • the null pointer value ([conv.ptr]) for that type, or
  • an invalid pointer value.

通过消除过程,我们可以推断出p是无效的指针值.

By the process of elimination we can deduce that p is an invalid pointer value.

[basic.stc] 说:

通过无效的指针值进行间接并传递无效的值 释放函数的指针值具有未定义的行为.任何 无效指针值的其他用法具有实现定义的 行为.

Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.

据说间接操作符是通过 [expr.]执行间接操作的. unary.op] ,我想说,无论是否使用结果,表达式*p都会导致UB.

As indirection operator is said to perform indirection by [expr.unary.op], I would say, that expression *p causes UB no matter if the result is used or not.

这篇关于如果没有发生左值到右值转换,是否取消引用无效指针是合法的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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