From d606311e5508ffccb0fb7e88537c8fe899f702ac Mon Sep 17 00:00:00 2001 From: Shawn Xu Date: Sun, 19 Jan 2025 17:55:53 -0800 Subject: [PATCH] Fix undefined behavior From cppreference: "It is undefined behavior to read from the member of the union that wasn't most recently written. Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union." closes https://github.com/official-stockfish/Stockfish/pull/5811 no functional change --- src/bitboard.h | 10 +++++----- src/misc.h | 7 ++----- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/src/bitboard.h b/src/bitboard.h index 6f9cca0b..df15113b 100644 --- a/src/bitboard.h +++ b/src/bitboard.h @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -268,11 +269,10 @@ inline int popcount(Bitboard b) { #ifndef USE_POPCNT - union { - Bitboard bb; - uint16_t u[4]; - } v = {b}; - return PopCnt16[v.u[0]] + PopCnt16[v.u[1]] + PopCnt16[v.u[2]] + PopCnt16[v.u[3]]; + std::uint16_t indices[4]; + std::memcpy(indices, &b, sizeof(b)); + return PopCnt16[indices[0]] + PopCnt16[indices[1]] + PopCnt16[indices[2]] + + PopCnt16[indices[3]]; #elif defined(_MSC_VER) diff --git a/src/misc.h b/src/misc.h index 81c7b17f..8adbac68 100644 --- a/src/misc.h +++ b/src/misc.h @@ -120,11 +120,8 @@ void sync_cout_start(); void sync_cout_end(); // True if and only if the binary is compiled on a little-endian machine -static inline const union { - uint32_t i; - char c[4]; -} Le = {0x01020304}; -static inline const bool IsLittleEndian = (Le.c[0] == 4); +static inline const std::uint16_t Le = 1; +static inline const bool IsLittleEndian = *reinterpret_cast(&Le) == 1; template