In my code (strict C, not C++), I use vsnprintf this way:
char* buf = NULL;
size_t sz;
sz = vsnprintf( buf, 0, format, args); // Ask vsnprintf how big a buffer we need
buf = (char*) malloc(sz + 1);
vsnprintf( buf, sz, format, args); // Now actually fill the buffer
/* Use buf in a dialog box... then: */
free(buf);
But MS Visual C++ (MSVS10) compiler warns:
warning C4996: 'vsnprintf': This function or variable may be unsafe. Consider using vsnprintf_s instead.
However, vsnprintf_s
does not have the nifty feature that when you pass NULL for the buffer it will describe how much data it would have printed. Instead, it is documented to return -1.
I feel I'm using vsnprintf
in a safe manner by determining the necessary size, and that the recommended replacement, vsnprintf_s
isn't the same at all.
Am I missing a better / smarter way to use vsnprintf_s
??
Turns out this question is pretty much an exact duplicate of:
Calculating the size of an sprintf() buffer
Summary of the answer:
Use _vscprintf
to figure out how big the buffer should be, then use vsnprintf_s
to actually fill it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With