Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Object passed as parameter when string is required in call to '*function*'
Remarks
This warning indicates that there's a mismatch between the format specifier and the type being used in a printf
-style function. The format specifier is a C style String type such as %s
or %ws
, and the argument is a class/struct/union type. This defect can lead to crashes, in addition to potentially incorrect output.
This defect is frequently due to forgetting to convert an object string type such as std::string
, CComBSTR
or bstr_t
into the C style string the printf
-style function expects. If so, then the fix is to add the appropriate conversion to the type. The conversion is needed because the variadic parameters to printf
-style functions are untyped, so no automatic conversion occurs.
Code analysis name: OBJECT_AS_STRING_ARGUMENT_TO_FORMAT_FUNCTION
Example
#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);
}
Fix the warning by adding the appropriate conversions:
#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());
}
See also
static_cast
Operator
sprintf_s
, _sprintf_s_l
, swprintf_s
, _swprintf_s_l
C4477
C4840