C++ Logo

std-proposals

Advanced search

Re: [std-proposals] [Idea] Null-terminated string view (c_str_view / c_wstr_view) – a simpler alternative/complement to zstring_view

From: Thiago Macieira <thiago_at_[hidden]>
Date: Wed, 04 Feb 2026 16:01:52 -0800
On Wednesday, 4 February 2026 14:41:29 Pacific Standard Time Ell via Std-
Proposals wrote:
> The problem isn't not respecting the size, it's deciding what the
> implications of saying that cstring_view can't have embedded nulls are
> in practice. I don't think that doing a strlen everywhere is the answer
> (or rather, I think that'll make cstring_view pretty useless).

I think it's reasonable to say that modifying the string that a cstring_view
points to is out of scope and need not be supported. The view object does not
have mutators anyway, so if it is happening, it's done using the original,
non-const pointer.

Therefore, implementations could hold a size member. That also means that
creating a string_view or cstring_view from an existing cstring_view can be
O(1) too.

What I insist on is that the creation of a cstring_view from something that
isn't by itself required to ban embedded NULs perform strlen. That's creation
from char pointers, string, and string_view. This is the whole raison d'être
of this class.

If I could instead declare that arbitrary string_views did not contain
embedded NULs, I could likewise just declare they are NUL-terminated and not
need to have a separate class.

> You deal with it the same way you deal with std::string allowing
> embedded nulls. You validate untrusted input, and then you probably
> assume there are none. And if your string does have unexpected embedded
> nulls then you already have a problem, truncating is just papering over
> it.

Right: since std::string allows embedded NULs (because it doesn't ban them), I
need to strlen() when receiving an arbitrary string before I can call it a C
string.

I agree that unexpected truncation is bad. But I argue that *not* truncating
is worse. For example, I could operate on the string starting from the end,
like so:
    if (domain.ends_with(".gov") || domain.ends_with(".mil")) {
        // must be secure!
        libcia_send_user_data(domain.c_str());
    }

An alternative is to make it a contract that strlen(str.data()) == str.size(),
failing at runtime if not, then providing means or guidance on how to create a
cstring_view from a larger buffer that may contain multiple embedded NULs.

BTW, is there a discussion on fine-grained contract control?
-- 
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
  Principal Engineer - Intel Data Center - Platform & Sys. Eng.

Received on 2026-02-05 00:02:03