Back to results for “Memory Management”
C++ › Strings & string_view

What are the dangers of std::string_view?

Intermediate

Answer

Because string_view doesn't own its data, it dangles if the underlying string is destroyed or modified (e.g., a view of a temporary, or of a std::string that reallocates). You must ensure the referenced data outlives the view. Also, string_view isn't guaranteed null-terminated, so don't pass its data() to C APIs expecting a null terminator.
std::string_view v = std::string("temp"); // dangles: temporary destroyed
Real-world example A string_view returned from a function referencing a local string dangles and reads freed memory.

Common follow-ups: Why can a string_view dangle? | Is string_view null-terminated?