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.
diff --git a/src/stdlib/SDL_string.c b/src/stdlib/SDL_string.c
index 9198cfe..0515fce 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) {