如果没有发生左值到右值转换,是否取消引用无效指针是合法的 [英] Is dereferencing invalid pointers legal if no lvalue-to-rvalue conversion occurs
问题描述
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?
我对此事
- 将整数投射到指针:对可以投射什么
- 间接:仅声明结果为左值.
- 生命周期:仅说明无法对对象执行的操作,有这里没有对象
- 表达式语句:
*p
是一个废弃的值表达式 - 舍弃的值表达式:不进行左值到右值转换 >
- 左值的不确定性:也就是严格的别名规则,仅当左值将转换为右值
- Casting integer to pointer: no restrictions on what may be casted
- Indirection: only states the result is a lvalue.
- Lifetimes: only states what can't be done on objects, there is no object here
- Expression statements:
*p
is a discarded value expression - Discarded value expressions: no lvalue-to-rvalue conversion occurs
- 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?
推荐答案
指针类型的每个值都是以下之一:
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屋!