メインコンテンツ

MISRA C++:2023 Rule 21.2.1

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

R2024b 以降

説明

ルール定義

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

根拠

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

  • 数値が含まれていない

  • 数値は含まれるが、範囲外の数値である

  • 数値の後にデータが続いている

atoi() などの C 標準ライブラリ関数を使用する場合、先行する入力にエラーがあると、未定義の動作が発生する可能性があります。ヘッダー <cstdlib> に含まれる atof()atoi()atoll()atoll() などの、文字列を数値に変換する関数の使用は避けてください。代わりに std::stoi()std::stof()std::stol() などの C++ 標準ライブラリ関数を使用します。

Polyspace 実装

Polyspace® は、文字列を数値に変換する C 標準ライブラリ関数 atoi()atol()atoll()、および atof() の使用にフラグを設定します。

トラブルシューティング

ルール違反が想定されるものの、Polyspace から報告されない場合は、コーディング規約違反が想定どおりに表示されない理由の診断を参照してください。

すべて展開する

#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  
	//...
} 

この例では、Polyspace は、文字列を数値に変換する C 標準ライブラリ関数の使用にフラグを設定します。次に例を示します。

  • 文字列を数値に変換する C 標準ライブラリ関数 (atoi()atof()atol() など) は、無効な変換によって未定義の動作が発生するため、非準拠としてフラグが設定されます。

  • 文字列を数値に変換する C++ 標準ライブラリ関数 (std::stoi()std::stof()std::stol() など) には、フラグが設定されません。無効な変換によって生成される std::invalid_argument 例外は、定義済みの動作であるためです。

チェック情報

グループ: 言語サポート ライブラリ
カテゴリ: 必要

バージョン履歴

R2024b で導入


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.