MSC13-C. 使用されない値を検出して削除する
使用されていない値の存在は、深刻な論理エラーを示す場合がある。この種のエラーを防ぐには、使用されていない値を特定してコードから削除する必要がある。
このレコメンデーションは「MSC12-C. プログラムに対して作用しないコードは検出して削除する」の具体的な事例である。
違反コード
以下のコードでは、p2 に bar() の返り値が代入されているが、この値は使用されていない。このコードは foo() と bar() が有効なポインタを返すことを想定している点に注意(「DCL30-C. 適切な記憶域期間を持つオブジェクトを宣言する」を参照)。
int *p1, *p2; p1 = foo(); p2 = bar(); if (baz()) { return p1; } else { p2 = p1; } return p2;
適合コード
修正方法は、プログラマの意図により異なる。以下の解決法では、p2 は無用であることがわかる。副作用がないならば、bar() と baz() の呼び出しは削除することができる。
/* bar() に副作用がないなら、削除可能 */ (void)bar(); /* baz() に副作用がないなら、削除可能 */ (void)baz(); return p1;
リスク評価
使用されない値は、深刻な論理エラーを示していることがある。
レコメンデーション | 深刻度 | 可能性 | 修正コスト | 優先度 | レベル |
---|---|---|---|---|---|
MSC13-C | 低 | 低 | 中 | P2 | L3 |
自動検出
LDRA tool suite Version 7.6.0 はこのレコメンデーションの違反を検出できる。
Coverity Prevent UNUSED_VALUE チェッカーは、関数呼び出しから返されたポインタ値が代入されているが使用されない変数を検出する。
Klocwork Version 8.0.4.16 では、IF_ONLY_DECL、IF_ONLY_DEF、IF_ONLY_LOCAL、LV_UNUSED.GEN、PA_UNUSED.GEN、VA_UNUSED.GEN、VA_UNUSED.INIT、および VA_UNUSED.INITCONST チェッカーを使ってこのレコメンデーションの違反を検出できる。
参考情報
- [Coverity 07]
- [ISO/IEC PDTR 24772] "BRS Leveraging human experience," "KOA Likely incorrect expressions," "XYQ Dead and Deactivated Code," and "XYR Unused Variable"
翻訳元
これは以下のページを翻訳したものです。