parts/6.64.UncontrolledFormatString-SHL.md

6.64 Uncontrolled Format String [SHL]

6.64.1 Applicability to language

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;
    getline(std::cin,line); // skip to eol
  }
}

In addition, operator overloading of output operators allows to extend formatting abilities to user-defined types.

6.64.2 Avoidance mechanisms for language users

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