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?
p2. Reason: You violate strict-aliasing. - Mysticialint long *p2??? what is long here? - Krishnabhadraint long *p2is a legitimate but slightly unorthodox way of writingsigned long int *p2,long *p2,long int *p2orlong int signed *p2(these are all equivalent to each other). - Jonathan Leffleriwill be aligned on an odd 32-bit address boundary butlongmust be aligned on a 64-bit address boundary (or even 32-bit address boundary). Therefore, on such systems, you would get a SIGBUS if you tried to read or modify memory viap2. - Jonathan Leffler