From 2d34f0f93a89e5e7ca10133a0be2ec09548babea Mon Sep 17 00:00:00 2001 From: Ben Wiederhake Date: Sun, 16 Aug 2020 07:47:33 +0200 Subject: [PATCH] LibC: Fix off-by-one in snprintf() snprintf is supposed to *always* NUL-terminate its output, so it has to write one output byte fewer. And yes, I *did* check all existing usages; this shouldn't break anything. --- Libraries/LibC/stdio.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Libraries/LibC/stdio.cpp b/Libraries/LibC/stdio.cpp index 53ee187fa6d..15d86dccc1f 100644 --- a/Libraries/LibC/stdio.cpp +++ b/Libraries/LibC/stdio.cpp @@ -889,10 +889,16 @@ ALWAYS_INLINE void sized_buffer_putch(char*& bufptr, char ch) int vsnprintf(char* buffer, size_t size, const char* fmt, va_list ap) { - __vsnprintf_space_remaining = size; + if (size) { + __vsnprintf_space_remaining = size - 1; + } else { + __vsnprintf_space_remaining = 0; + } int ret = printf_internal(sized_buffer_putch, buffer, fmt, ap); if (__vsnprintf_space_remaining) { buffer[ret] = '\0'; + } else if (size > 0) { + buffer[size - 1] = '\0'; } return ret; }