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
This commit is contained in:
Shawn Xu
2025-01-19 17:55:53 -08:00
committed by Joost VandeVondele
parent aa894c0f93
commit d606311e55
2 changed files with 7 additions and 10 deletions
+5 -5
View File
@@ -22,6 +22,7 @@
#include <algorithm> #include <algorithm>
#include <cassert> #include <cassert>
#include <cmath> #include <cmath>
#include <cstring>
#include <cstdint> #include <cstdint>
#include <cstdlib> #include <cstdlib>
#include <string> #include <string>
@@ -268,11 +269,10 @@ inline int popcount(Bitboard b) {
#ifndef USE_POPCNT #ifndef USE_POPCNT
union { std::uint16_t indices[4];
Bitboard bb; std::memcpy(indices, &b, sizeof(b));
uint16_t u[4]; return PopCnt16[indices[0]] + PopCnt16[indices[1]] + PopCnt16[indices[2]]
} v = {b}; + PopCnt16[indices[3]];
return PopCnt16[v.u[0]] + PopCnt16[v.u[1]] + PopCnt16[v.u[2]] + PopCnt16[v.u[3]];
#elif defined(_MSC_VER) #elif defined(_MSC_VER)
+2 -5
View File
@@ -120,11 +120,8 @@ void sync_cout_start();
void sync_cout_end(); void sync_cout_end();
// True if and only if the binary is compiled on a little-endian machine // True if and only if the binary is compiled on a little-endian machine
static inline const union { static inline const std::uint16_t Le = 1;
uint32_t i; static inline const bool IsLittleEndian = *reinterpret_cast<const char*>(&Le) == 1;
char c[4];
} Le = {0x01020304};
static inline const bool IsLittleEndian = (Le.c[0] == 4);
template<typename T, std::size_t MaxSize> template<typename T, std::size_t MaxSize>