Skip to content

Intermediate Gotchas

The View That Printed Past Its End

five visible characters, eleven printed ones

int main() {
  std::string_view label = "black,white";
  std::string_view first = label.substr(0, 5);

  std::cout << first.data() << '\n';
}

What does the five-character view print?

Answer
black,white

The view ends after black, but its pointer does not.

Why

string_view::substr returns a view with an adjusted pointer and length; it does not write a terminator after the new end. data() gives operator<<(const char*) only a pointer, so that overload scans through the original literal's terminator. Streaming the string_view itself uses its stored length. For a view without a later terminator, passing data() to a C-string API can read beyond its character sequence and is undefined behavior.

The fix

std::cout << first << '\n';

Takeaway: a string_view has a pointer and a length; data() alone is not a C-string.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Quiz this entry