format string is not a string literal in a variadic template function (C++)

Viewed 90

I have this simple function, in which I get an error:

format string is not a string literal (potentially insecure) [-Werror,-Wformat-security]

I know that I can make a C-style variadic function and use:

__attribute__((__format__ (__printf__, x, y)))

but I have to keep it in C++ template style.

Are there any workarounds for this problem? I tried:

printf("%s", boost::str((boost::format(inputString) % ... % args)).c_str());

but it doesn't work the same as printf(). EDIT: It doesnt work the same because i handles types differently:

    uint8_t a = 1;
    printf("%s", boost::str(boost::format("%u") % a ).c_str()); //this wont print anything, because %u doesnt match uint_8t
    printf("%u",a); //this will print 1
template <typename... Types>
inline static void log(const char* inputString, Types... args)
{
    printf(inputString, args...);
}
1 Answers

Ok, I think that generally good solutions for this problem are the ones written above in comments, but what worked for me with my project constrains was:

#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat"
#endif
template <typename... Types>
void log(const char* inputString, Types... args)
{
    printf(inputString, args...);
}
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
Related