[flac-dev] vsnprintf_s and vsnprintf
Erik de Castro Lopo
mle+la at mega-nerd.com
Sat Sep 20 04:23:56 PDT 2014
lvqcl wrote:
> I wrote a small program that fills a buffer[] with "abcdefghijklmnopqrstuvwxyz\0"
> pattern and then tries to write "0123456789" string into it.
> It calls either
> ret = vsnprintf_s(buffer, buf_size, _TRUNCATE, fmt, va);
> or
> ret = vsnprintf(buffer, buf_size, fmt, va);
<snip>
> vsnprintf (MSVC, MinGW):
>
> buf_size = 8; ret = -1; buffer = "01234567ijklmnopqrstuvwxyz"
> buf_size = 9; ret = -1; buffer = "012345678jklmnopqrstuvwxyz"
> buf_size = 10; ret = 10; buffer = "0123456789klmnopqrstuvwxyz"
> buf_size = 11; ret = 10; buffer = "0123456789"
> buf_size = 12; ret = 10; buffer = "0123456789"
This is actually the only one we can use.
With a check on the the return value and a line or two of extra
code, this function can made to behave resonably sensibly, even it
its not possible to make it meet the requirements if the ISO C specs.
I'm basically think of something like the (untested) diff below.
Erik
diff --git a/src/share/grabbag/snprintf.c b/src/share/grabbag/snprintf.c
index 3a0661f..6a4e3ea 100644
--- a/src/share/grabbag/snprintf.c
+++ b/src/share/grabbag/snprintf.c
@@ -62,8 +62,11 @@ flac_snprintf(char *str, size_t size, const char *fmt, ...)
va_start (va, fmt);
#ifdef _MSC_VER
- rc = vsnprintf_s (str, size, _TRUNCATE, fmt, va);
- rc = (rc > 0) ? rc : (size == 0 ? 1024 : size * 2);
+ rc = vsnprintf (str, size, fmt, va);
+ if (rc < 0) {
+ rc = size - 1;
+ str [rc] = 0;
+ }
#else
rc = vsnprintf (str, size, fmt, va);
#endif
--
----------------------------------------------------------------------
Erik de Castro Lopo
http://www.mega-nerd.com/
More information about the flac-dev
mailing list