-
Notifications
You must be signed in to change notification settings - Fork 15.7k
Description
This program, when compiled with DEBUG hardening -O0 -std=c++2c -stdlib=libc++ -DNDEBUG -D _LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_DEBUG provokes assertion failure in clang-20 and clang-21 and current trunk (2025-09-24, clang version 22.0.0git (https://github.com/llvm/llvm-project.git 89d2b7e)).
Godbolt: https://godbolt.org/z/9MPhM7vr5
Only sizes being multiples of 256 fail, as it seems, formatting is done in chunks of 256 bytes and then __size_ == __capacity_ (== 256) (cf. https://github.com/llvm/llvm-project/blob/main/libcxx/include/__format/buffer.h#L211).
The problem doesn't happen with std::format or size not being multiples of 256 (certainly due to __container_inserter_buffer having this size, cf. https://github.com/llvm/llvm-project/blob/main/libcxx/include/__format/buffer.h#L461).
#include <print>
#include <string>
int main() {
std::string vsmall(255, 'b');
std::string v(512, 'b'); // any multiple of 256 fails
std::string vlarge(257, 'b');
std::string buf;
std::ignore = std::format("'{}'", v); // OK
std::format_to(std::back_inserter(buf), "'{}'", vsmall); // OK
std::format_to(std::back_inserter(buf), "'{}'", vlarge); // OK
// BAD: assertion in __format/buffer.h:211:
std::format_to(std::back_inserter(buf), "'{}'", v);
return 0;
}
Failure:
/cefs/2d/2d07650fd93fff193e184eee_clang-trunk-20250924/bin/../include/c++/v1/__format/buffer.h:210: libc++ Hardening assertion __ptr_ && __size_ < __capacity_ && __available() >= 1 failed: attempted to write outside the buffer
Program terminated with signal: SIGSEGV