Reputation: 34632
A (very long) while ago I regularly used the following code - then on MSVC 6 - to determine the memory needed to format a string for a function with variadic arguments:
void LogPrint(const char *pszFormat, ...)
{
int nBytes;
char *pszBuffer;
va_list args;
va_start(args, pszFormat);
nBytes = vsnprintf(0, 0, pszFormat, va);
va_end(args);
// error checking omitted for brevity
pszBuffer = new char[nBytes + 1];
va_start(args, pszFormat);
vsnprintf(pszBuffer, nBytes, pszFormat, va);
va_end();
// ...
}
The obvious error you're getting in a more recent version of MSVC (I'm using 2010 now) is:
warning C4996: 'vsnprintf': This function or variable may be unsafe. Consider using vsnprintf_s instead. To disable deprecation use _CRT_SECURE_NO_WARNINGS. See online help for details.
I'm a big fan of the "treat warnings as errors" option for any C(++)-compiler, and obviously my build fails. It feels like cheating to me to simply employ #pragma warning (disable:4996)
and get on with it.
The suggested "safer" alternative vsnprintf_s()
, however is doomed to return -1
when input conditions of its "unsafe" predecessor occur.
TL/DR: Is there a way to implement the expected behavior of vsnprintf()
to return the memory needed to fulfil its task using the new, safer variants of it?
EDIT: simply defining _CRT_SECURE_NO_WARNINGS
won't cut it; there's a lot of strcpy()
flying around, too. The new variant of which isn't broken, so I'd like to still see these.
Upvotes: 10
Views: 8736
Reputation: 31306
The function you want to look at is _vscprintf
, which "returns the number of characters that would be generated if the string pointed to by the list of arguments was printed or sent to a file or buffer using the specified formatting codes". There's a widechar variant (_vscwprintf
) as well.
Upvotes: 15