diff --git a/Python/sysmodule.c b/Python/sysmodule.c index 8b27b37b76b..faa63ab7a3d 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -1023,13 +1023,20 @@ mywrite(char *name, FILE *fp, const char *format, va_list va) vfprintf(fp, format, va); else { char buffer[1001]; - int written = PyOS_vsnprintf(buffer, sizeof(buffer), - format, va); + const int written = PyOS_vsnprintf(buffer, sizeof(buffer), + format, va); + const int trouble = written < 0 || written >= sizeof(buffer); + if (trouble) { + /* Ensure there's a trailing null byte -- MS + vsnprintf fills the buffer to the very end + if it's not big enough. */ + buffer[sizeof(buffer) - 1] = '\0'; + } if (PyFile_WriteString(buffer, file) != 0) { PyErr_Clear(); fputs(buffer, fp); } - if (written == -1 || written > sizeof(buffer)) { + if (trouble) { const char *truncated = "... truncated"; if (PyFile_WriteString(truncated, file) != 0) { PyErr_Clear();