小さい頃はエラ呼吸

いつのまにやら肺で呼吸をしています。


【cppcheck】error: Undefined behavior: Variable 'xxx' is used as parameter and destination in s[n]printf().

はじめに

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関数の出力先バッファと入力バッファは別々の変数にするようにしましょう。