From c83b388a3f8f7a8c8d5a5cfddb6ab397005371a1 Mon Sep 17 00:00:00 2001 From: Laslo Hunhold Date: Thu, 17 May 2018 23:23:28 +0200 Subject: Properly handle *snprintf() errors Posix guarantees that the resulting string is null-terminated, even if we have an overflow. Instead of doing what has already been done, properly warn when there has been an error or overflow, so the user can do something about it. --- util.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'util.c') diff --git a/util.c b/util.c index 8808aba..6113049 100644 --- a/util.c +++ b/util.c @@ -10,15 +10,15 @@ const char * bprintf(const char *fmt, ...) { va_list ap; - size_t len; + int ret; va_start(ap, fmt); - len = vsnprintf(buf, sizeof(buf) - 1, fmt, ap); - va_end(ap); - - if (len >= sizeof(buf)) { - buf[sizeof(buf)-1] = '\0'; + if ((ret = vsnprintf(buf, sizeof(buf), fmt, ap)) < 0) { + fprintf(stderr, "vsnprintf: %s\n", strerror(errno)); + } else if ((size_t)ret >= sizeof(buf)) { + fprintf(stderr, "vsnprintf: Output truncated\n"); } + va_end(ap); return buf; } -- cgit v1.2.3