Skip to content

[libc++] Internal failure in std::format_to when passing a string of size being a multiple of 256 #160666

@mk-huawei

Description

@mk-huawei

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    formatC++20 std::format or std::print, and anything related to themlibc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions