MSC31-C. 関数の返り値は必ず適切な型と比較する
関数の返り値を比較する際には、同じ型のリテラル定数と比較する必要がある。しかし、C 言語仕様では、返り値の型が部分的にしか規定されていない場合がある。「算術型」や「符号無し整数」のような表現で規定されている場合、実装上は複数の選択肢があり、具体的にどの型で実装するかは処理系の自由である。たとえば unsigned char
型や unsigned short
型として実装されている場合、アーキテクチャによっては、-1
のような整数リテラルと等価にならないことがある。
違反コード (time_t
)
time()
関数は、時刻が取得できない場合に (time_t)(-1)
を返す。C 言語仕様は、time_t
型が時刻を表現できる算術型であるということのみ要求している。時刻を表現するのに使用すべき最適な算術型の決定は、処理系側に任されている。time_t
が符号付き int
より小さい符号無し整数型として実装された場合、time()
の返り値は、整数リテラル -1
と等しくはならない。
#include <time.h> void func(void) { time_t now = time(NULL); if (now != -1) { /* 処理を続ける */ } }
適合コード (time_t
)
正しく比較するためには、time()
の返り値を time_t
にキャストした -1
と比較しなければならない。
#include <time.h> void func(void) { time_t now = time(NULL); if (now != (time_t)-1) { /* 処理を続ける */ } }
この適合コードは「INT18-C. より大きいサイズの整数との比較や代入を行う前に、整数式をそのサイズで評価する」に適合している。
違反コード (size_t
)
mbstowcs()
関数はマルチバイト文字列をワイド文字の文字列に変換し、変換された文字数を返す。無効なマルチバイト文字が見つかると、mbstowcs()
は (size_t)(-1)
を返す。size_t
の実装次第だが、mbstowcs()
の戻り値を符号付き整数リテラル -1
と比較したときに、期待通りに評価されない場合がある。
#include <stdlib.h> void func(wchar_t *pwcs, const char *restrict s, size_t n) { size_t count_modified = mbstowcs(pwcs, s, n); if (count_modified == -1) { /* エラー処理 */ } }
適合コード(size_t
)
比較を確実に正しく実行するには、mbstowcs()
の返り値を、size_t
でキャストした -1
と比較しなければならない。
#include <stdlib.h> void func(wchar_t *pwcs, const char *restrict s, size_t n) { size_t count_modified = mbstowcs(pwcs, s, n); if (count_modified == (size_t)-1) { /* エラー処理 */ } }
この適合コードは「INT18-C. 整数式をより大きなサイズの整数に対して比較や代入をする際には、事前に演算後のサイズで評価する」に適合している。
リスク評価
返り値を異なる型の値と比較すると、計算を誤り意図しないプログラム動作やプログラムの異常終了につながる可能性がある。
ルール |
深刻度 |
可能性 |
修正コスト |
優先度 |
レベル |
---|---|---|---|---|---|
MSC31-C |
低 |
中 |
中 |
P4 |
L3 |
自動検出(最新の情報はこちら)
ツール |
バージョン |
チェッカー |
説明 |
---|---|---|---|
Compass/ROSE |
|
|
|
LDRA tool suite |
8.5.4 |
456 S |
実装済み |
PRQA QA-C | 8.1 | 1253 | 部分的に実装済み |
関連するガイドライン
CERT C コーディングスタンダード | INT18-C. より大きいサイズの整数との比較や代入を行う前に、整数式をそのサイズで評価する |
CERT C++ Secure Coding Standard | VOID MSC31-CPP. Ensure that return values are compared against the proper type |
MITRE CWE | CWE-697, Insufficient comparison CWE-704, Incorrect type conversion or cast |
参考資料
[Kettlewell 2002] | Section 4, "Type Assumptions" |
[Pfaff 2004] | |
[SecuriTeam 2007] |
翻訳元
これは以下のページを翻訳したものです。
VOID MSC31-C. Ensure that return values are compared against the proper type (revision 133)