Is vsnprintf_s a suitable replacement for legacy vsnprintf?

In my code (strict C, not C ++) I use vsnprintf as follows:

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 the MS Visual C ++ compiler (MSVS10) warns:

 warning C4996: 'vsnprintf': This function or variable may be unsafe. Consider using vsnprintf_s instead. 

However, vsnprintf_s does not have a great function, which, when you pass NULL to the buffer, will describe how much data would be printed. Instead, it is documented to return -1 .

I feel that I am using vsnprintf safe manner, determining the required size and the recommended replacement of vsnprintf_s not the same.

Am I missing a better / smarter way to use vsnprintf_s ??

+4
source share
2 answers

It turns out this question is pretty much an exact duplicate:

Sprintf () buffer size calculation

Summary of answer:

Use _vscprintf to find out how big the buffer is, and then use vsnprintf_s to actually fill it.

+3
source

VC has finally implemented the vsnprintf standard. See the always untrusted version of MSDN .

0
source

Source: https://habr.com/ru/post/1488573/


All Articles