From 880842cfdf4df9ff673e91c1ac2a9a4c30e4db52 Mon Sep 17 00:00:00 2001 From: Sam Lantinga Date: Sat, 31 Dec 2016 16:14:51 -0800 Subject: [PATCH] Fixed bug 3531 - internal SDL_vsnprintf implementation access memory outside given buffer ranges Tristan The internal SDL_vsnprintf implementation accesses memory outside buffer. The bug existed also inside the format (%) processing, which was fixed with Bug 3441. But there is still an invalid access, if we do not have any format inside the source string and the destination string is shorter than the format string. You can use any string for this test, as long it is longer than the buffer. Example: va_list argList; char buffer[4]; SDL_vsnprintf(buffer, sizeof(buffer), "Testing", argList); The bug is located on the 'else' branch of the format char test: while (*fmt) { if (*fmt == '%') { ... } else { if (left > 1) { *text = *fmt; --left; } ++fmt; ++text; } } if (left > 0) { *text = '\0'; } As you can see that text is always incremented, even when left is already one. When then on the last lines, *text is assigned the NULL char, the pointer is located outside bounds. --- src/stdlib/SDL_string.c | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/stdlib/SDL_string.c b/src/stdlib/SDL_string.c index 9198cfeaf..0515fce7b 100644 --- a/src/stdlib/SDL_string.c +++ b/src/stdlib/SDL_string.c @@ -1484,7 +1484,7 @@ SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt, if (!fmt) { fmt = ""; } - while (*fmt) { + while (*fmt && left > 1) { if (*fmt == '%') { SDL_bool done = SDL_FALSE; size_t len = 0; @@ -1646,12 +1646,8 @@ SDL_vsnprintf(SDL_OUT_Z_CAP(maxlen) char *text, size_t maxlen, const char *fmt, left -= len; } } else { - if (left > 1) { - *text = *fmt; - --left; - } - ++fmt; - ++text; + *text++ = *fmt++; + --left; } } if (left > 0) {