はじめに
C++の静的解析ツール「cppcheck」でソースコードを静的解析した場合に、以下の警告がでることがあります。
error: Buffer is accessed out of bounds.
cppcheckのバージョン
- v1.65
サンプルプログラム
以下のソースプログラムを解析にかけると表示されます。
int _tmain(int argc, _TCHAR* argv[]) { char tmp[4]; //NG //char tmp[5]; // OK int num = 100; sprintf(tmp, "%04d", num); printf("%s\n", tmp); return 0; }
上記のように、4byteのバッファに対して、sprintf(tmp, "%04d", num);で書き込みしようとすると最後に¥0が付加されるので、1byteバッファをオーバしてしまいます。
関連記事
- 【cppcheck】Invalid memcmp() argument nr 3. A non-boolean value is required.
- 【cppcheck】 (warning) Logical disjunction always evaluates to true
- 【cppcheck】(warning) Found calculation inside sizeof().
- C6305の解説 sizeof 数と countof 数の間で不一致が発生した可能性があります
- 【cppcheck】Variable 'xxx' is reassigned a value before the old one has been used.