取消引用null是否不总是UB? [英] Dereference null is not always UB?
问题描述
我一直以标准要求取消引用null
的事实为UB.但是,
I've always known for a fact that the Standard mandates dereferencing null
is UB. However,
p = 0; * p;并不是天生的错误.
p = 0; *p; is not inherently an error.
并提供指向的链接
* p在p为null时不是错误,除非将左值转换为左值
*p is not an error when p is null unless the lvalue is converted to an lvalue
(我相信这是一个错字,应该将 lvalue转换为 rvalue )
(I believe it's a typo and probably should read lvalue is converted to an rvalue)
链接1也说
char * p = 0; char * q =& *(p)
char* p = 0; char *q = &*(p)
是未定义的",我只能读为定义明确的或至少是实现定义的
is "not undefined", which I could only read as well-defined or at least implementation-defined
语言律师可以对发生的事情提供权威的解释吗?
Can a language lawyer provide an authoritative explanation of what's going on?
推荐答案
I explored the topic of indirection through null pointers in this answer. In short, it is indeed well-defined per se, just as elaborated in your cited Core issues. The committee used the notion of an empty lvalue as proposed many years ago (but never adopted); *p
is supposed to be such an empty lvalue, and unless we attempt to access the (non-existent) memory location behind that lvalue (for example, by performing an lvalue-to-rvalue conversion), all other operations behave as expected. E.g. &*p
is equivalent to p
, unless p
is invalid. (This also works for pointers past-the-end of an array, which is necessary for the common idiom &arr[n]
).
我还开始起草用于空左值的纸张(这是WIP,还没有完成针对N4640的重新部署),因此我们有机会在稍后的阶段中看到更多内容.
I also started drafting a paper for empty lvalues (this is WIP, and the rebase against N4640 isn't complete yet), so there's a chance we'll see more of this at a later stage.
这篇关于取消引用null是否不总是UB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!