diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py index 5d322cb444cfb68..2642000558abab9 100644 --- a/Lib/test/test_format.py +++ b/Lib/test/test_format.py @@ -318,6 +318,8 @@ def test_common_format(self): "format argument 1: too big for width") test_exc_common('%*r', (-2**1000, 1), OverflowError, "format argument 1: too big for width") + test_exc_common('%*r', (-maxsize - 1, 1), OverflowError, + "format argument 1: too big for width") test_exc_common('%.*r', (2**1000, 1), OverflowError, "format argument 1: too big for precision") test_exc_common('%.*r', (-2**1000, 1), OverflowError, diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-23-23-24.gh-issue-151847.5uNKTL.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-23-23-24.gh-issue-151847.5uNKTL.rst new file mode 100644 index 000000000000000..a815071108a46eb --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-23-23-24.gh-issue-151847.5uNKTL.rst @@ -0,0 +1,3 @@ +When formatting a ``str`` or ``bytes`` with ``%``, passing ``-sys.maxsize - +1`` as the width previously negated it, this is undefined behaviour in C. It +now raises :exc:`OverflowError`. diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c index f63185e14284b1a..041d1e612a7d364 100644 --- a/Objects/bytesobject.c +++ b/Objects/bytesobject.c @@ -803,6 +803,11 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len, } if (width < 0) { flags |= F_LJUST; + if (width < -PY_SSIZE_T_MAX) { + FORMAT_ERROR(PyExc_OverflowError, + "too big for width%s", ""); + goto error; + } width = -width; } if (--fmtcnt >= 0) diff --git a/Objects/unicode_format.c b/Objects/unicode_format.c index e2790c8c1d4343d..9d70c091daeb67a 100644 --- a/Objects/unicode_format.c +++ b/Objects/unicode_format.c @@ -560,6 +560,10 @@ unicode_format_arg_parse(struct unicode_formatter_t *ctx, } if (arg->width < 0) { arg->flags |= F_LJUST; + if (arg->width < -PY_SSIZE_T_MAX) { + FORMAT_ERROR(PyExc_OverflowError, "too big for width%s", ""); + return -1; + } arg->width = -arg->width; } if (--ctx->fmtcnt >= 0) {