The vulnerability as described in ISO/IEC 24772-1 is applicable to C++.
C++ inherits the C libraries which provide a large family of input and output functions that use a control string to interpret the data read or format the output. These strings include all the feature described in ISO/IEC TR 24772-1:2019 clause 6.64.1.
C++ provides type-safe alternatives for input/output, which do not use format strings and which should be used in preference, such as
int aNumber{};
while(std::cin){ // is input still available
std::cout << "Enter a whole number, please:";
if (std::cin >> aNumber) { // no format string needed
std::cout >> "Thank you, the number can be represented as "
std::cout << std::format("0b{0:b} {0:d} 0{0:o} 0x{0:x}", aNumber);
else { // input failed
} std::cin.clear(); // re-enable input
std::string line;
std::cin,line); // skip to eol
getline(
} }
In addition, operator overloading of output operators allows to extend formatting abilities to user-defined types.
To avoid the vulnerability or mitigate its ill effects, C++ software developers can:
Forbid the use of the C library facilities provided by <cstdio>
.
Use the avoidance mechanisms provided by the standard library as described in ISO/IEC 14882 20.20 Formatting [format] or similar libraries, if printf-style formatting of output or strings is desired, or when the formatting facilities of std::ostream
are inadequate.
Read untrusted input as plain characters and then check for validity, before any conversion to numbers or program entities occurs, using facilities that do not require format strings and that check and report error conditions.