Skip to content

Conversation

@mszeszko-meta
Copy link
Contributor

@mszeszko-meta mszeszko-meta commented Jan 27, 2026

Work around a warning/linter false positive related to the use of string::insert. The code in question is legal C++, but GCC 12's libstdc++ implementation of string::insert internally uses memcpy, which can trigger undefined behavior warnings when the source and destination overlap.

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.
@meta-codesync
Copy link

meta-codesync bot commented Jan 27, 2026

@mszeszko-meta has imported this pull request. If you are a Meta employee, you can view this in D91594561.

@mszeszko-meta mszeszko-meta changed the title Fix -Werror=restrict build failure in UniqueIdToHumanString with GCC 12 Work around GCC 12 false positive warning for string::insert Jan 27, 2026
Copy link
Contributor

@pdillinger pdillinger left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see existing unit tests for this function, so 👍

@meta-codesync
Copy link

meta-codesync bot commented Jan 27, 2026

@mszeszko-meta merged this pull request in acfea34.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants