The vulnerability as documented in ISO/IEC TR 24772-1:2019 exists in C++ when C-style strings are used. For example, passing a non-null-terminated character array to an interface that requires a null-terminated string can result in undefined behaviour [EWF]. 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)
{// okay string has termination character
puts(s.data()); // not okay; string termination not guaranteed
puts(sv.data()); }
To avoid the vulnerability or mitigate its ill effects, C++ software developers can:
Avoid C-style strings.
If using C-style strings is unavoidable, use the avoidance mechanisms of ISO/IEC 24772-3 clause 6.7.2.
Ensure that explicit overflow checks are performed for all string operations.
Prefer using a string type, e.g., std::string
, which manages the memory of its string and handles termination in order to mitigate against this vulnerability.
Don’t use the underlying raw pointer of a std::string_view
or a std::span
with interfaces that expect C-style strings.
Use static analysis tools to help identify occurrences of undefined behaviour.