MSC04-C. コメントの記法には一貫性を持たせ読みやすくする
違反コード
コメントの中で /* を使用しないこと。
/* コメント終了マーカが意図せず省略されている security_critical_function(); /* ほかのコメント */
この例では、security_critical_function の呼び出しは行われないが、コードレビュー時にこの関数が実行されるものと誤解される可能性がある。
これが誤って省略された結果である場合、構文の強調表示機能やコードの書式設定機能のあるエディタを使うと、コメント終了文字列の欠落のような問題の特定に役立つ。
終了文字列の省略は、エラーを招きやすく間違いと見なされることが多いため、この方法でコードをコメントアウトしないほうがよい。
適合コード (プリプロセッサ)
/* と */ を使用してコードをコメントアウトする代わりに、条件付きのコンパイル(たとえば #if、#ifdef、#ifndef など)を使用してコメントアウトする。
#if 0 /* critical_security_function の使用は * 不要になった */ security_critical_function(); /* ほかのコメント */ #endif
#if、#ifdef、または #ifndef を使用してコメントアウトされているコード内のテキストも有効な前処理字句で構成されている必要がある。つまり、文字 " および ' は C のコード内の文字と同じようにそれぞれ対になっている必要があり、対が行の境界を超えてはならない。特に、短縮語のアポストロフィは文字定数の先頭のように見える可能性がある。そのため、通常の言語でのコメントや擬似コードは、必ずコメント区切り文字 /* および */ の間、または // のあとに書かねばならない。
適合コード (コンパイラ)
以下の解決法は、到達不可能なコード(デッドコード)を削除するコンパイラ機能を使用している。if 文で囲まれるコードは、依然としてコンパイラに受け付けられなければならない。マクロ、型、関数プロトタイプなど、プログラムのほかの部分が後で変更され、それが原因で構文の誤りが生じる可能性がある場合は、実行されないコードを最新の状態に更新して問題を修正しておく必要がある。その後、実行されないコードが将来再度必要になった場合は、コードを囲む if 文と NOTREACHED コメントを削除するだけでよい。
NOTREACHED コメントは、一部のコンパイラと静的解析ツールに対してこの到達不能コードについてエラーを出さないことを伝える。また、説明の役割も果たす。
if (0) { /* critical_security_function の使用は * 当面不要になった */ /*NOTREACHED*/ security_critical_function(); /* ほかのコメント */ }
これは「MSC07-C. デッドコードを検出して削除する」の例外 MSC07-EX2 である。
違反コード
以下に示すコメントの書き方は、混乱を招きやすいため避けるべきである。
// */ /* コメント。構文誤りではない */ f = g/**//h; /* f = g / h; に 等しい */ //\ i(); /* 2 行に渡るコメントの一部 */ /\ / j(); /* 2 行に渡るコメントの一部 */ /*//*/ l(); /* l(); に等しい */ m = n//**/o + p; /* m = n + p; に等しい */ a = b //*divisor:*/c +d; /* C90 では a = b/c +d; と解釈される * C99 では a = b+d と解釈される */
適合コード
コメントには一貫した記述方法を使用する。
/* シンプルでわかりやすいコメント */ int i; /* カウンタ */
リスク評価
実行される命令と実行されない命令の混乱が原因で深刻なプログラミングエラーが引き起こされ、サービス運用妨害、プログラムの異常終了、データの不整合などの脆弱性につながる可能性がある。対話型の開発環境(IDE)を使用したり、エディタの機能を使用して書体や色などでコメントとコードを区別したりすることでこの問題を緩和することができる。ただし、たとえば白黒印刷されたソースコードを見直す場合などには依然として問題が残る。
レコメンデーション | 深刻度 | 可能性 | 修正コスト | 優先度 | レベル |
---|---|---|---|---|---|
MSC04-C | 中 | 低 | 中 | P4 | L3 |
自動検出
LDRA tool suite V 7.6.0 はこのレコメンデーションの違反を検出できる。
-Wcomment フラグを使用すると、GCC はこのレコメンデーションの違反を検出できる。
参考情報
- [ISO/IEC 9899:1999] Section 6.4.9, "Comments," and Section 6.10.1, "Conditional inclusion"
- [MISRA 04] Rule 2.2, "Source code shall only use /* ... */ style comments," Rule 2.3, "The character sequence /* shall not be used within a comment," and Rule 2.4, "Sections of code should not be commented out"
- [Summit 05] Question 11.19
翻訳元
これは以下のページを翻訳したものです。
MSC04-C. Use comments consistently and in a readable fashion