No, the new code still has undefined behaviour. C11 6.3.2.3p7:
- A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned 68) for the referenced type, the behavior is undefined. […]
It doesn’t say anything about dereferencing the pointer – even the conversion has undefined behaviour.
Indeed, the modified code that you assume is ARM-safe might not be even Intel-safe. Compilers are known to generate code for Intel that can crash on unaligned access. While not in the linked case, it might just be that a clever compiler can take the conversion as a proof that the address is indeed aligned and use a specialized code for memcpy
.
Alignment aside, your first excerpt also suffers from strict aliasing violation. C11 6.5p7:
- An object shall have its stored value accessed only by an lvalue expression that has one of the following types:88)
- a type compatible with the effective type of the object,
- a qualified version of a type compatible with the effective type of
the object,- a type that is the signed or unsigned type
corresponding to the effective type of the object,- a type that
is the signed or unsigned type corresponding to a qualified version of
the effective type of the object,- an aggregate or union type
that includes one of the aforementioned types among its members
(including, recursively, a member of a subaggregate or contained
union), or- a character type.
Since the array buf[2048]
is statically typed, each element being char
, and therefore the effective types of the elements are char
; you may access the contents of the array only as characters, not as int32_t
s.
I.e., even
int32_t nextWord = *((int32_t *) &buf[_Alignof(int32_t)]);
has undefined behaviour.