Main Content

MISRA C++:2023 Rule 21.2.1

The library functions atof, atoi, atol and atoll from <cstdlib> shall not be used

Since R2024b

Description

Rule Definition

The library functions atof, atoi, atol and atoll from <cstdlib> shall not be used.

Rationale

Converting strings to a numeric value can result in error conditions, for instance, when the input string:

  • Does not contain a number

  • Contains a number, but is out of range

  • Contains additional data after a number

If you use C standard library functions such as atoi(), the preceding input errors might result in undefined behavior. Avoid using string-to-number functions such as atof(), atoi(), atoll(), and atoll() from the header <cstdlib>. Use C++ standard library functions, such as std::stoi(), std::stof(), and std::stol() instead.

Polyspace Implementation

Polyspace® flags the use of C standard library string-to-number functions of atoi(), atol(), atoll(), and atof().

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

#include <cstdlib> 
#include <iostream> 
#include <string> 

void foo() { 
	std::string str1 = "7"; 
	std::string str2 = "3.1415"; 
	std::string str3 = "three"; 

	int myint1 = std::stoi(str1);       //Compliant 
	float myint2 = std::stof(str2);     //Compliant 
	long myint3 = std::stol(str3);      //Compliant 

	const char* str4 = "12"; 
	const char* str5 = "2.7182"; 
	const char* str6 = "undefinedError"; 

	int num4 = atoi(str4);              //Noncompliant 
	float num5 = atof(str5);            //Noncompliant 
	long num6 = atol(str6);             //Noncompliant  
	//...
} 

In this example, Polyspace flags the use of C standard library functions for converting strings to numeric value. For instance:

  • The string-to-number functions from the C standard library, such as atoi(), atof(), and atol() are noncompliant flagged because an invalid conversion results in undefined behavior.

  • The string-to-number functions from the C++ standard library std::stoi(), std::stof(), and std::stol() are not flagged because an invalid conversion produces a std::invalid_argument exception, which is defined behavior.

Check Information

Group: Language support library
Category: Required

Version History

Introduced in R2024b