'*function*' の呼び出しで文字列が必要な場合にパラメーターとして渡されるオブジェクト
解説
この警告は、書式指定子と、 printf スタイルの関数で使用されている型の間に不一致があることを示します。 書式指定子は、 %s や %wsなどの C スタイルの文字列型で、引数はクラス/構造体/共用体型です。 この欠陥が原因で、出力が正しくなくなる可能性に加えて、クラッシュする可能性もあります。
この問題は、 std::string、 CComBSTR 、 bstr_t などのオブジェクト文字列型を、 printfスタイルの関数が想定する C スタイルの文字列に変換し忘れることが原因で発生する場合がよく発生します。 その場合、修正は型に適切な変換を追加します。
printfスタイルの関数への可変引数パラメーターは型指定されていないため、自動変換は行われません。
コード分析名: OBJECT_AS_STRING_ARGUMENT_TO_FORMAT_FUNCTION
例
次の例では C6284 が生成されます。
#include <atlbase.h>
#include <string>
void f()
{
char buff[50];
CComBSTR bstrValue{"Hello"};
std::string str{"World"};
// Oops, %ws and %s require C-style strings but CComBSTR and std::strings are being passed instead
sprintf(buff, "%ws %s", bstrValue, str);
}
適切な変換を追加して、警告を修正します。
#include <atlbase.h>
#include <string>
void f()
{
char buff[50];
CComBSTR bstrValue{"Hello"};
std::string str{"World"};
// Fixed by adding a static_cast to the CComBSTR and calling c_str() on the std::string
sprintf(buff, "%ws %s", static_cast<wchar_t*>(bstrValue), str.c_str());
}
関連項目
static_cast 演算子
sprintf_s、 _sprintf_s_l、 swprintf_s、 _swprintf_s_l
C4477
C4840