diff --git a/include/boost/endian/buffers.hpp b/include/boost/endian/buffers.hpp index 081aee8..258bbec 100644 --- a/include/boost/endian/buffers.hpp +++ b/include/boost/endian/buffers.hpp @@ -47,6 +47,7 @@ #include #include #include +#include # if CHAR_BIT != 8 # error Platforms with CHAR_BIT != 8 are not supported @@ -295,7 +296,12 @@ namespace endian // case since sizeof(T) and n_bytes are known at compile // time. { - return *reinterpret_cast(bytes); + // Avoids -fsanitize=undefined violations due to unaligned loads + // All major x86 compilers optimize a short-sized memcpy into a single instruction + + T t; + std::memcpy( &t, bytes, sizeof(T) ); + return t; } # endif return unrolled_byte_loops::load_little @@ -321,7 +327,10 @@ namespace endian // case since sizeof(T) and n_bytes are known at compile // time. { - *reinterpret_cast(bytes) = value; + // Avoids -fsanitize=undefined violations due to unaligned stores + // All major x86 compilers optimize a short-sized memcpy into a single instruction + + std::memcpy( bytes, &value, sizeof(T) ); return; } # endif