Why is gcc allowed to speculatively load from a struct?

前端 未结 6 768
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  •  渐次进展
    2021-02-06 21:26

    This is always allowed under the "as-if" rule if no conforming program can tell the difference. For example, an implementation could guarantee that after each block allocated with malloc, there are at least eight bytes that can be accessed without side effects. In that situation, the compiler can generate code that would be undefined behaviour if you wrote it in your code. So it would be legal for the compiler to read P[1] whenever P[0] is correctly allocated, even if that would be undefined behaviour in your own code.

    But in your case, if you don't allocate enough memory for a struct, then reading any member is undefined behaviour. So here the compiler is allowed to do this, even if reading P->B crashes.

提交回复
热议问题