From 8db4723355b8fa0c9736892a73b9516e14297d5f Mon Sep 17 00:00:00 2001 From: Maciej Szeszko Date: Tue, 27 Jan 2026 08:41:00 -0800 Subject: [PATCH] Fix -Werror=restrict build failure in UniqueIdToHumanString with GCC 12 GCC 12's stricter -Wrestrict analysis detects potential overlapping memory regions in std::string::insert() when shifting characters within the same buffer. This triggers build failures on: - CentOS 7 (x86_64 and aarch64) with GCC 12.1.1 - Alpine 3.18 (PPC64le) with GCC 12.2.1 The issue occurs because insert(pos, str) must shift all characters from position pos to the end rightward to make room for the new content. This shifting copies from [pos, end) to [pos+len, end+len) within the same buffer - overlapping regions. The libstdc++ implementation uses memcpy (via char_traits::copy) for this operation, but memcpy has undefined behavior when source and destination overlap. push_back() does not have this problem because it only appends to the end of the string. No existing characters need to be moved, so there are no overlapping memory regions. Fix by building the output string incrementally using push_back() instead of modifying in-place with insert(). This also eliminates repeated character shifting, making it slightly more efficient. --- table/unique_id.cc | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/table/unique_id.cc b/table/unique_id.cc index 8bfa8bcfd383..758ad574e948 100644 --- a/table/unique_id.cc +++ b/table/unique_id.cc @@ -199,12 +199,16 @@ Status GetUniqueIdFromTableProperties(const TableProperties &props, } std::string UniqueIdToHumanString(const std::string &id) { - // Not so efficient, but that's OK - std::string str = Slice(id).ToString(/*hex*/ true); - for (size_t i = 16; i < str.size(); i += 17) { - str.insert(i, "-"); + std::string hex = Slice(id).ToString(/*hex*/ true); + std::string result; + result.reserve(hex.size() + hex.size() / 16); + for (size_t i = 0; i < hex.size(); i++) { + if (i > 0 && i % 16 == 0) { + result.push_back('-'); + } + result.push_back(hex[i]); } - return str; + return result; } std::string InternalUniqueIdToHumanString(UniqueIdPtr in) {