Skip to content

<format>: Should we verify character arrays being null-terminated when creating basic_format_arg? #5094

Open
@frederick-vs-ja

Description

@frederick-vs-ja

There're Preconditions specified in [format.arg]/5 for constructing a basic_format_arg:

Preconditions: If decay_t<T> is char_type* or const char_type*, static_cast<const char_type*>(v) points to a NTCTS ([defns.ntcts]).

And character arrays are decayed per [format.arg]/6.9:

otherwise, if decay_t<TD> is char_type* or const char_type*, initializes value with static_cast<const char_type*>(v);

It seems that we can check the content of the array (of known bound) in this internal factory function.

// Function template _Make_from mirrors the exposition-only single-argument constructor template of
// basic_format_arg (N4950 [format.arg]).
template <_Formattable_with<_Context> _Ty>
_NODISCARD static basic_format_arg _Make_from(_Ty& _Val) noexcept {
using _Erased_type = _Format_arg_traits<_Context>::template _Storage_type<_Ty>;
if constexpr (is_same_v<remove_const_t<_Ty>, char> && is_same_v<_CharType, wchar_t>) {
return basic_format_arg(static_cast<_Erased_type>(static_cast<unsigned char>(_Val)));
}
#if !_HAS_CXX23
else if constexpr (is_same_v<_Erased_type, basic_string_view<_CharType>>) {
return basic_format_arg(_Erased_type{_Val.data(), _Val.size()});
}
#endif // !_HAS_CXX23
else {
return basic_format_arg(static_cast<_Erased_type>(_Val));
}
}

Should we verify that the array is null-terminated? Note that the checking is not O(1) but still seems cheap in formatting to me.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementSomething can be improvedformatC++20/23 format

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions