Why is gcc allowed to speculatively load from a struct?

前端 未结 6 753
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-06 20:29

Example Showing the gcc Optimization and User Code that May Fault

The function \'foo\' in the snippet below will load only one of the struct members A or B; well at le

6条回答
  •  -上瘾入骨i
    2021-02-06 21:29

    This is perfectly legal because reading some memory location isn't considered an observable behavior in the general case (volatile would change this).

    Your example code is indeed undefined behavior, but I can't find any passage in the standard docs that explicitly states this. But I think it's enough to have a look at the rules for effective types ... from N1570, §6.5 p6:

    If a value is stored into an object having no declared type through an lvalue having a type that is not a character type, then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value.

    So, your write access to *P actually gives that object the type Pair -- therefore it just extends into memory you didn't allocate, the result is an out of bounds access.

提交回复
热议问题