SDL: Fixed infinite loop in SDL_vsnprintf() if the format string is too large for the output buffer

From dc4c7d9539fc65ace92c76a2d1536451685b74b8 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Wed, 10 Nov 2021 09:48:49 -0800
Subject: [PATCH] Fixed infinite loop in SDL_vsnprintf() if the format string
 is too large for the output buffer

Fixes https://github.com/libsdl-org/SDL/issues/4940
---
 src/stdlib/SDL_string.c      | 3 ++-
 test/testautomation_stdlib.c | 6 ++++++
 2 files changed, 8 insertions(+), 1 deletion(-)

diff --git a/src/stdlib/SDL_string.c b/src/stdlib/SDL_string.c
index cc25cc83c6..6922a24a9f 100644
--- a/src/stdlib/SDL_string.c
+++ b/src/stdlib/SDL_string.c
@@ -1887,8 +1887,9 @@ SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt,
             }
         } else {
             if (length < maxlen) {
-                text[length] = *fmt++;
+                text[length] = *fmt;
             }
+            ++fmt;
             ++length;
         }
     }
diff --git a/test/testautomation_stdlib.c b/test/testautomation_stdlib.c
index 608d92fc2b..bfc8ad373d 100644
--- a/test/testautomation_stdlib.c
+++ b/test/testautomation_stdlib.c
@@ -64,6 +64,12 @@ stdlib_snprintf(void *arg)
   SDLTest_AssertPass("Call to SDL_snprintf(NULL, 0, \"%%s\", \"foo\")");
   SDLTest_AssertCheck(result == 3, "Check result value, expected: 3, got: %d", result);
 
+  result = SDL_snprintf(text, 2, "%s\n", "foo");
+  expected = "f";
+  SDLTest_AssertPass("Call to SDL_snprintf(\"%%s\\n\", \"foo\") with buffer size 2");
+  SDLTest_AssertCheck(SDL_strcmp(text, expected) == 0, "Check text, expected: %s, got: %s", expected, text);
+  SDLTest_AssertCheck(result == 4, "Check result value, expected: 4, got: %d", result);
+
   result = SDL_snprintf(text, sizeof(text), "%f", 0.0);
   predicted = SDL_snprintf(NULL, 0, "%f", 0.0);
   expected = "0.000000";