Undefined behavior on reading object using non-character type when last written using character type

后端 未结 2 2048
生来不讨喜
生来不讨喜 2020-12-09 09:13

Assuming unsigned int has no trap representations, do either or both of the statements marked (A) and (B) below provoke undefined behavior, why or why not, and

2条回答
  •  既然无缘
    2020-12-09 09:53

    On a superficial examination, I'd agree with your assessment (A is UB, B is fine), and can offer a concrete rationale for why that should be so (prior to the edit to include _Alignas()): Alignment.

    The char[] on the stack can start at any address, whether that's a valid alignment for an unsigned int or not. In contrast, malloc() is required to return memory meeting the strictest alignment requirements of any native type on the platform in question.

    The standard obviously doesn't want to impose alignment requirements on char[] beyond those of char, so it has to leave type-punned access to it as potentially undefined.

提交回复
热议问题