STR37-C. 文字処理関数への引数は unsigned char として表現できなければならない
C 標準 [ISO/IEC 9899:2011] セクション 7.4 には次のように記載されている。
ヘッダ
<ctype.h>では、文字の分類やマッピングに便利な関数が宣言されている。引数はすべてint型であり、その値はunsigned char型として表現可能であるか、マクロEOFの値と等しくなければならない。引数がそれ以外の値を持つ場合、動作は未定義である
(附属書 J 「未定義の動作」の 113 も参照)。
char データ型は処理系により signed か unsigned のいずれかであるため、このルールへ適合するのはむずかしい。
次の文字分類関数が対象となる。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
注意: XSI とは、ISO/IEC 9945—POSIX への X/Open システムインタフェース拡張を指す。この関数は C 標準では定義されていない。
「STR34-C. 文字データをより大きなサイズの整数型に変換するときは事前に unsigned char 型に変換する」はこのルールを汎用化したものである。
違反コード
以下のコード例では、isspace() 関数に無効な値が渡される可能性がある。
size_t count_preceding_whitespace(const char *s) {
const char *t = s;
/* *t < 0 かもしれない */
while (*t && isspace(*t)) {
++t;
}
return t - s;
}
isspace() の引数は EOF、または unsigned char として表現可能な値でなければならない。それ以外の場合、結果は未定義となる。
適合コード
以下の適合コードでは、isspace() 関数の引数を unsigned char 型にキャストしている。
size_t count_preceding_whitespace(const char *s) {
const char *t = s;
while (*t && isspace((unsigned char)*t)) {
++t;
}
return t - s;
}
リスク評価
unsigned char 型で表現できない値を文字処理関数に渡すと、意図しないプログラム動作を引き起こす可能性がある。
|
ルール |
深刻度 |
可能性 |
修正コスト |
優先度 |
レベル |
|---|---|---|---|---|---|
|
STR37-C |
低 |
低 |
低 |
P3 |
L3 |
自動検出(最新の情報はこちら)
|
ツール |
バージョン |
チェッカー |
説明 |
|---|---|---|---|
|
Compass/ROSE |
上に挙げた関数の引数が |
||
|
ECLAIR |
1.1 |
idb_charplan |
実装済み |
| PRQA QA-C | 8.1 | STR34 の特殊ケース | 実装済み |
関連するガイドライン
| CERT C++ Secure Coding Standard | STR37-CPP. Arguments to character handling functions must be representable as an unsigned char |
| ISO/IEC TS 17961 (ドラフト) | Passing arguments to character-handling functions that are not representable as unsigned char [chrsgnext] |
| MITRE CWE | CWE-704, Incorrect type conversion or cast CWE-686, Function call with incorrect argument type |
参考資料
| [ISO/IEC 9899:2011] | Section 7.4, "Character Handling <ctype.h>" |
| [Kettlewell 2002] | Section 1.1, "<ctype.h> and Characters Types" |
翻訳元
これは以下のページを翻訳したものです。
STR37-C. Arguments to character handling functions must be representable as an unsigned char (revision 75)



