parts/6.07.StringTermination-CJM.md

6.7 String Termination [CJM]

6.7.1 Applicability to language

The vulnerability as documented in ISO/IEC TR 24772-1:2019 exists in C++ when C-style strings are used, e.g., with interfaces that require NUL-terminated strings. C++ provides alternative string processing capabilities that do not exhibit those vulnerabilities.

C++ provides a class template for string processing, std::basic_string that manages the space for the string and the string length and always includes a string termination character. For example, when concatenating, the std::basic_string object will increase in size to contain the resulting string. Futhermore, as the string is guaranteed to have a string termination character, using its underlying raw pointer as a C-style string will mitigate this vulnerability because the string termination character is present.

C++ provides the library class templates std::basic_stringview and std::span that implement reference semantics to non-owned buffers. These types do not rely on a string termination character to determine the length of the string, thus, use of these types avoids those vulnerabilities. However, using its underlying raw pointer as a C-style string can result in these vulnerabilities because the string termination character is not guaranteed to be present.

void foo(std::string const& s, std::string_view const& sv)
{
  puts(s.data());  // okay string has termination character
  puts(sv.data()); // not okay; string termination not guaranteed
}

6.7.2 Avoidance mechanisms for language users

To avoid the vulnerability or mitigate its ill effects, C++ software developers can: