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
1 #include <iostream> 2 using namespace std; 3 void f1() { 4 int i, j; 5 std::cin >> i >> j; //uncompliant code 6 cin >>i>>j; //uncompliant code 7 // ... 8 } 9 10 void f2() { 11 int i, j; 12 13 std::cin.exceptions(std::istream::failbit | std::istream::badbit); 14 try { // Use try catch to process exceptions. It is compliant. 15 std::cin >> i >> j; 16 // ... 17 } catch (std::istream::failure &E) { 18 // Handle error 19 } 20 } 21 22 void f3() { 23 int i; 24 std::cin >> i; 25 if (i>0 && std::cin.fail()) { 26 // Handle failure to convert the value. It is compliant. 27 std::cin.clear(); 28 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ' '); 29 } 30 31 int j; 32 std::cin >> j; 33 if (cin.fail()) { 34 std::cin.clear(); 35 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ' '); 36 } 37 38 // ... 39 }