The conversion to a wrongly aligned pointer itself is undefined, not only a load through that pointer (C11 (n1570) 6.3.2.3 p7):
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 [...] for the referenced type, the behavior is undefined.
The code shown also breaks strict aliasing, as the pointed-to object is unlikely to be declared as uintptr_t
(the address would be correctly aligned otherwise).
To be standard conforming, unsigned char
can be used instead.
If uintptr_t
-sized chunks shall be copied for performance reasons, unsigned char
can be used until the address is properly aligned, followed by another loop copying uintptr_t
. This should be done through a union or via memcpy
to avoid aliasing issues (Gcc can optimize memcpy
calls out if the size is constant). The last bytes may need to be copied via unsigned char
again to avoid out-of-bounds access (a read sizeof(uintptr_t)-1
bytes past the array shouldn't cause problems (Glibc does this in several places), but the write through dst
may write into another object). It may help to restrict
-qualify the pointers used.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…