Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is vsnprintf_s an appropriate replacement for deprecated vsnprintf?

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??

like image 874
abelenky Avatar asked Jun 27 '13 19:06

abelenky


1 Answers

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.

like image 170
abelenky Avatar answered Sep 20 '22 09:09

abelenky