[PATCH] libstdc++: implement LWG3662 basic_string::append/assign(NTBS, pos, n) suboptimal

Tomasz Kaminski tkaminsk@redhat.com
Wed Jul 1 15:42:00 GMT 2026


On Wed, Jul 1, 2026 at 5:26 PM Jonathan Wakely <jwakely.gcc@gmail.com>
wrote:

>
>
> On Wed, 1 Jul 2026, 16:19 Nathan Myers, <ncm@cantrip.org> wrote:
>
>> On 7/1/26 11:08 AM, Jonathan Wakely wrote:
>> > On Wed, 1 Jul 2026 at 15:47, Tomasz Kaminski <tkaminsk@redhat.com>
>> wrote:
>> >>
>> >> Are the following checks correct? I think we need string of at least
>> length __pos + __len.
>> >
>> > The macro is defined as:
>> > #  define __glibcxx_requires_string_len(_String,_Len)    \
>> >    _GLIBCXX_DEBUG_PEDASSERT(_String != 0 || _Len == 0)
>> >
>> > So it says we can't have a null pointer unless n==0 is true. I think
>> > that's the right check here.
>> >
>> >
>> >
>> >> __glibcxx_requires_string_len(__s, __n);
>>
>>
>> I was a little worried about
>>
>>    return assign(__sv_type(__s).substr(__pos, __n));
>>
>> It will scan all the way to the end of __s to make the string_view,
>> and then only use __n of that. Shouldn't it limit the size of the
>> string_view?
>>
>
> We find have strnlen in char_traits. This was discussed by lwg and is
> mentioned in the issue.
>
To expand, if we assume that range [p, __n + __pos) is valid, we could use
char_traits::find(p, __n + __pos, _CharT()) to find an embedded null in the
range,
and if there is not any construct basic_string_view from (p, __n + __pos).

However, the behavior of this function is well defined if you pass NTBS
that is shorter
than __pos + __n (throws on __pos, and trims __n). So we will introduce a
new UB
by doing above.

>
>
>
>> Maybe to __pos + __n; or even to __n and start it at __s + __pos
>> if predconditions allow.
>>
>
> They don't.
>
> Consider append("a\0b", 2, 1) which should throw out_of_range.
>
>
>
>> >> On Wed, Jul 1, 2026 at 4:41 PM Yuao Ma <addr2line@gmail.com> wrote:
>> >>>
>> >>> Hi!
>> >>>
>> >>> This patch implements LWG3662 for C++11 ABI and COW ABI of strings.
>> >>>
>> >>> Tested on x86_64 linux, ok for trunk?
>> >>>
>> >>> Thanks,
>> >>> Yuao
>> >
>>
>>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://gcc.gnu.org/pipermail/libstdc++/attachments/20260701/f30fcaec/attachment.htm>


More information about the Libstdc++ mailing list