From 115b8e214a0d7b22e63dfce130268ce2c96c7d03 Mon Sep 17 00:00:00 2001 From: Kawe Mazidjatari <48657826+Mauler125@users.noreply.github.com> Date: Tue, 6 Feb 2024 14:36:01 +0100 Subject: [PATCH] utility: fix STL string formatter bug Must reserve a buf size of len+1 before resizing it, else we are 1 byte too short when copying the entire string. Also just clear when 0. --- r5dev/tier0/utility.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/r5dev/tier0/utility.cpp b/r5dev/tier0/utility.cpp index dab4e454..f3105773 100644 --- a/r5dev/tier0/utility.cpp +++ b/r5dev/tier0/utility.cpp @@ -1086,14 +1086,20 @@ string FormatV(const char* szFormat, va_list args) assert(iLen >= 0); string result; - if (iLen < 0) + if (iLen <= 0) { result.clear(); } else { + // NOTE: reserve enough buffer size for the string + the terminating + // NULL character, then resize it to just the string len so we don't + // count the NULL character in the string's size (i.e. when calling + // string::size()). + result.reserve(iLen+1); result.resize(iLen); - std::vsnprintf(&result[0], iLen+sizeof(char), szFormat, args); + + std::vsnprintf(&result[0], iLen+1, szFormat, args); } return result;