From e5474a557974bd50481812e9a5892be853384d4c Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 6 Oct 2025 00:08:23 +0200 Subject: [PATCH 1/3] Fix unaligned memory access UB in compact_vector::access() Replace reinterpret_cast + dereference with memcpy to avoid undefined behavior when accessing unaligned uint64_t values. This fixes crashes and incorrect behavior on ARM64 where unaligned access is not tolerated. The memcpy approach is standards-compliant and compilers optimize it to efficient code on all platforms. --- include/compact_vector.hpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/include/compact_vector.hpp b/include/compact_vector.hpp index 59c1753..75db609 100644 --- a/include/compact_vector.hpp +++ b/include/compact_vector.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include "essentials.hpp" @@ -253,7 +254,9 @@ struct compact_vector // assert(i < size()); uint64_t pos = i * m_width; const char* ptr = reinterpret_cast(m_data.data()); - return (*(reinterpret_cast(ptr + (pos >> 3))) >> (pos & 7)) & m_mask; + uint64_t word; + std::memcpy(&word, ptr + (pos >> 3), sizeof(uint64_t)); + return (word >> (pos & 7)) & m_mask; } uint64_t back() const { return operator[](size() - 1); } From e16cea2998984fab6839ae269c3c727950b969c6 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 6 Oct 2025 00:15:05 +0200 Subject: [PATCH 2/3] fix UB in append_bits --- include/bit_vector.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/include/bit_vector.hpp b/include/bit_vector.hpp index ba0fb57..ea303ec 100644 --- a/include/bit_vector.hpp +++ b/include/bit_vector.hpp @@ -97,7 +97,7 @@ struct bit_vector // void append_bits(uint64_t bits, uint64_t len) { // check there are no spurious bits - assert(len == 64 || (bits >> len) == 0); + assert(len >= 64 || (bits >> len) == 0); if (!len) return; uint64_t pos_in_word = m_num_bits & 63; m_num_bits += len; From 74fb6937690adcd88f089f624b15362257cccf07 Mon Sep 17 00:00:00 2001 From: Oleksandr Kulkov Date: Mon, 6 Oct 2025 18:55:31 +0200 Subject: [PATCH 3/3] Fix assert --- include/bit_vector.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/include/bit_vector.hpp b/include/bit_vector.hpp index ea303ec..9cd515f 100644 --- a/include/bit_vector.hpp +++ b/include/bit_vector.hpp @@ -97,7 +97,8 @@ struct bit_vector // void append_bits(uint64_t bits, uint64_t len) { // check there are no spurious bits - assert(len >= 64 || (bits >> len) == 0); + assert(len <= 64); + assert(len == 64 || (bits >> len) == 0); if (!len) return; uint64_t pos_in_word = m_num_bits & 63; m_num_bits += len;