CERT.ERR.CONV.STR_TO_NUM

Detect errors when converting a string to a number.

When calling a formatted input stream function like istream::operator>>(), information about conversion errors is queried through the basic_ios::good(), basic_ios::bad(), and basic_ios::fail() inherited member functions or through exception handling if it is enabled on the stream object.

Vulnerability and risk

The process of parsing an integer or floating-point number from a string can produce many errors. The string might not contain a number. It might contain a number of the correct type that is out of range (such as an integer that is larger than INT_MAX). The string may also contain extra information after the number, which may or may not be useful after the conversion.

Mitigation and prevention

Always explicitly check the error state of a conversion from string to a numeric value (or handle the related exception, if applicable) instead of assuming the conversion results in a valid value.

Example

Copy
  #include <iostream>
  using namespace std;
  void f1() {
    int i, j;
    std::cin >> i >> j;   //uncompliant code
    cin >>i>>j;    //uncompliant code
    // ...
  }
  
 void f2() {
   int i, j;
 
   std::cin.exceptions(std::istream::failbit | std::istream::badbit);
   try {               // Use try catch to process exceptions. It is compliant.
     std::cin >> i >> j;
     // ...
   } catch (std::istream::failure &E) {
     // Handle error
   }
 }
 
 void f3() {
   int i;
   std::cin >> i;
   if (i>0 && std::cin.fail()) {
     // Handle failure to convert the value. It is compliant.
     std::cin.clear();
     std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
   }
 
   int j;
   std::cin >> j;
   if (cin.fail()) {
     std::cin.clear();
     std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
   }
 
   // ...
 }