From e93f6a22703249f0ebfff25302147c64965d5907 Mon Sep 17 00:00:00 2001 From: Peter Dimov Date: Sat, 23 Dec 2017 18:40:09 +0200 Subject: [PATCH] Fix unaligned loads and stores --- include/boost/endian/buffers.hpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) 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