https://github.com/python/cpython/commit/182f3231542e84fd1b0c795898f69f61fe35df0e
commit: 182f3231542e84fd1b0c795898f69f61fe35df0e
branch: main
author: Victor Stinner <[email protected]>
committer: vstinner <[email protected]>
date: 2026-10-05T03:09:25Z
summary:

gh-158585: Adjust _PyBytes_FormatEx() allocation (#158823)

Count properly the number of preallocated bytes when growing the
buffer.

files:
M Lib/test/test_bytes.py
M Objects/bytesobject.c

diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py
index f87a924c57016e..96190a7f582170 100644
--- a/Lib/test/test_bytes.py
+++ b/Lib/test/test_bytes.py
@@ -894,7 +894,7 @@ def __int__(self):
     def test_memory_leak_gh_140939(self):
         # gh-140939: MemoryError is raised without leaking
         _testcapi = import_helper.import_module('_testcapi')
-        with self.assertRaises(MemoryError):
+        with self.assertRaises((MemoryError, OverflowError)):
             b = self.type2test(b'%*b')
             b % (_testcapi.PY_SSIZE_T_MAX, b'abc')
 
diff --git a/Objects/bytesobject.c b/Objects/bytesobject.c
index 9bd9afc9b51ba4..1917055d25198f 100644
--- a/Objects/bytesobject.c
+++ b/Objects/bytesobject.c
@@ -747,6 +747,7 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len,
             char onechar; /* For byte_converter() */
             Py_ssize_t alloc;
 
+            const char *start = fmt;
             fmt++;
             if (*fmt == '%') {
                 *res++ = '%';
@@ -1108,9 +1109,10 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t 
format_len,
             alloc = width;
             if (sign != 0 && len == width)
                 alloc++;
-            /* 2: size preallocated for %s */
-            if (alloc > 2) {
-                res = PyBytesWriter_GrowAndUpdatePointer(writer, alloc - 2, 
res);
+            /* size preallocated for the format */
+            Py_ssize_t prealloc = fmt - start;
+            if (alloc > prealloc) {
+                res = PyBytesWriter_GrowAndUpdatePointer(writer, alloc - 
prealloc, res);
                 if (res == NULL) {
                     Py_XDECREF(temp);
                     goto error;

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to