int i = 42;
int *p1 = &i;
int long *p2 = (long*)p1;
Is this undefined behavior? In C++, I think it is implementation defined behavior for some reason.
I looked in C Standard:
C99 6.3.2.3/7 A pointer to an object or incomplete type may be
converted to a pointer to a different object or incomplete type. If
the resulting pointer is not correctly aligned 57) for the pointed-to
type, the behavior is undefined. Otherwise, when converted back again,
the result shall compare equal to the original pointer.57) In general, the concept “correctly aligned” is transitive: if a
pointer to type A is correctly aligned for a pointer to type B, which
in turn is correctly aligned for a pointer to type C, then a pointer
to type A is correctly aligned for a pointer to type C.
What does the term correctly aligned mean here in practice? How do you know if you’re doing it correctly without stepping into Undefined behavior?
It basically means that if, say,
intis aligned to 4 bytes, andint longis aligned to 8 bytes, the behavior is undefined. Say you have something like:In this case,
&i == 0x0C(which is valid becauseintis aligned to 4 bytes). When you cast toint long*, the pointer is converted to an aligned one:p2 == 0x08, because our theoretical system alignsint longto 8 bytes, so you’d be basically reading off an address you don’t own if you dereferencep1, ergo the undefined behavior.