From 3c6f64b26be49392210b642da6f542005c6e76e7 Mon Sep 17 00:00:00 2001 From: Bill Currie Date: Thu, 3 Jan 2002 23:24:47 +0000 Subject: [PATCH] _snprintf and _vsnprintf are not guaranteed to write the trailing '\0' --- include/compat.h | 4 ++-- libs/util/string.c | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/include/compat.h b/include/compat.h index 9326a876e..0f4a15779 100644 --- a/include/compat.h +++ b/include/compat.h @@ -58,11 +58,11 @@ /* These may be underscored... */ #if defined(HAVE__SNPRINTF) # undef snprintf -# define snprintf _snprintf +# define snprintf Q_snprintfz #endif #if defined(HAVE__VSNPRINTF) # undef vsnprintf -# define vsnprintf _vsnprintf +# define vsnprintf Q_vsnprintfz #endif #if defined(_WIN32) && !defined(__BORLANDC__) # define kbhit _kbhit diff --git a/libs/util/string.c b/libs/util/string.c index d58fe26a2..5ea861ad0 100644 --- a/libs/util/string.c +++ b/libs/util/string.c @@ -65,3 +65,29 @@ Q_strnlen (const char *s, size_t maxlen) for (i = 0; i < maxlen && s[i]; i++); return i; } + +#ifdef HAVE__VSNPRINTF +void +Q_snprintfz (char *dest, size_t size, char *fmt, ...) +{ + int len; + va_list argptr; + + va_start (argptr, fmt); + len = _vsnprintf (dest, size - 1, fmt, argptr); + va_end (argptr); + if (len < 0) // the string didn't fit into the buffer + dest[size - 1] = 0; +} + +void +Q_vsnprintfz (char *dest, size_t size, va_list argptr) +{ + int len; + + len = _vsnprintf (dest, size - 1, fmt, argptr); + + if (len < 0) // the string didn't fit into the buffer + dest[size - 1] = 0; +} +#endif