はじめに
C++の静的解析ツール「cppcheck」でソースコードを静的解析した場合に、以下の警告がでることがあります。
error: Undefined behavior: Variable 'xxx' is used as parameter and destination in s[n]printf().
cppcheckのバージョン
- v1.66
サンプルプログラム
以下のソースプログラムを解析にかけると表示されます。
#include "stdafx.h" #include <windows.h> int _tmain(int argc, _TCHAR *argv[]) { char szBuff[256] = { 0 }; sprintf(szBuff, "%s %s", szBuff, "hoge"); //->error: Undefined behavior: Variable 'szBuff' is used as parameter and destination in s[n]printf(). printf("%s\n", szBuff); return 0; }
上記のように、sprintfの出力先バッファと入力バッファが同じ場合、"予期しない動作になりますよ"という警告がでます。
sprintf関数の出力先バッファと入力バッファは別々の変数にするようにしましょう。
関連記事
- (warning) The 2nd memset() argument '8224' doesn't fit into an 'unsigned char'.
- 【C++】構造体のサイズとバイトアライメント
- C++のコードレビューで使いたい、コードの品質を向上させる3つの方法
- 【cppcheck】A pointer can not be negative so it is either pointless or an error to check if it is
- 【cppcheck】(error) Buffer overrun possible for long command line arguments.