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
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.
The authors of the Standard acknowledge in the rationale that it would be possible for an implementation to be conforming but useless. Because they expected that implementers would endeavor to make their implementations useful, they didn't think it necessary to mandate every behavior that might be needed to make an implementation suitable for any particular purpose.
The Standard imposes no requirements on the behavior of code that accesses an aligned object of character-array type as some other type. That doesn't mean that they intended that implementations should do something other than treat the array as untyped storage in cases where code takes the address of the array once but never accesses it directly. The fundamental nature of aliasing is that it requires that an item be accessed in two different ways; if an object is only ever accessed one way, there is by definition no aliasing. Any quality implementation which is supposed to be suitable for low-level programming should behave in useful fashion in cases where a char[]
is used only as untyped storage, whether the Standard requires it or not, and its hard to imagine any useful purpose that would be impeded by such treatment. The only purpose that would be served by having the Standard mandate such behavior would be to prevent compiler writers from treating the lack of a mandate as being--in and of itself--a reason not to process such code in the obvious useful fashion.