r/cpp • • Oct 16 '18

Unaligned accesses in C/C++: what, why and solutions to do it properly

https://blog.quarkslab.com/unaligned-accesses-in-cc-what-why-and-solutions-to-do-it-properly.html
3 Upvotes

3 comments sorted by

23

u/OldWolf2 Oct 16 '18

Urgh, so many mistakes here...

  • "C/C++" isn't a language. There is the C language and the C++ language. They have different rules about alignment. In fact C++ doesn't have any rules about aligned accesses. But it's moot because you cannot express an unaligned access in code without causing UB by violating other rules, e.g. the strict aliasing rule or the object lifetime rules.

  • The code *((uint64_t const*)V) is undefined behaviour due to strict aliasing violation (in both languages)

  • An "objection" to the memcpy solution is that a builtin is "required" for endian support, however the aliasing version would have the exact same issue (if it weren't undefined as mentioned above).

  • The conclusion is a load of rubbish too, the C and C++ languages both have compiler optimization as a core principle. The languages are defined in terms of program output, not in terms of intermediate assembly instructions. Literally any code you write , the compiler "could" generate inefficient code. In which case, you would report a compiler bug or use a better compiler. This situation isn't a special case.

The correct solution is just to memcpy it. There is a wrapper for this use case proposed for C++20, std::bit_cast.

2

u/MrWhite26 Oct 25 '18

After trying all sorts of 'smart' things, indeed memcpy it is : https://godbolt.org/z/qyGFXo

Those smart things were mostly optimized correctly by gcc, clang. for MSVC memcpy is the one that works.

2

u/henri05 Oct 18 '18

Do you have any reference about C and C++ having different alignment rules? According to cppreference, C++ do have alignment constraints on objects. In the end, althought C and C++ are different languages, it could be interesting to figure out if they are the same on this matter. Moreover, I think the author do point the fact that the memcpy solution needs builtins..