Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Strict aliasing rule
#1
The Rule 11.3 (category Required) disallows the conversion between two pointers to different object types, indicating in the first paragraph the possible problems due to different alignment, and in the second paragraph that even if same alignment it is undefined behavior anyway (citing C99 section 6.5p7), except if conversion to pointer to a char type.

Even if the rule is technically correct, in my opinion readers will normally focus on the first paragraph, just analysing the alignment restrictions (and endianness) of the specific platform for justifying specific deviations (like using type punning through pointer conversion for needed format conversions). For example, justifying the conversion of a uint32_t into an array of two uint16_t, or a 32-bit float into a uint32_t. However, the part about undefined behavior is probably not highlighted enough, specially now that current compilers will take advantage of this undefined behavior to generate broken code due to the type aliasing analysis (reordering assignments or even removing code as the compiler is not required to consider the dependencies between those objects due to the undefined behavior, unless aliasing through a char pointer type or due to a few other exceptions).

I think it would be much more useful for the reader to mention the "strict aliasing rule" (as this is the term normally used to warn about these problems in technical forums) and the possibility to get "miscompiled" code at high optimization levels. Also, I think it would be very appreciated to give some guidance of possible standard-compliant solutions like using memcpy instead (moreover as the compiler will probably remove the call overhead if optimizations enabled), copying into an union (which may also be optimized by the compiler, not really generating any data copy) if the compiler is compliant with C99 T3, or even disabling the strict aliasing when compiling (like using -fno-strict-aliasing in GCC), in addition to the already mentioned access through a pointer to a char type.  Even if it cannot be ensured the universal adequacy of these solutions, the readers will be warned about sophisticated compilers and the strict aliasing rule, and will be aware about possible solutions available to be considered in their specific platform. Thank you very much.

Best regards,
Santiago
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)