Skip to content

Commit 6e1569b

Browse files
committed
gh-158585: Adjust _PyBytes_FormatEx() allocation
Count properly the number of preallocated bytes when growing the buffer.
1 parent 5fecd44 commit 6e1569b

2 files changed

Lines changed: 6 additions & 4 deletions

File tree

‎Lib/test/test_bytes.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -894,7 +894,7 @@ def __int__(self):
894894
def test_memory_leak_gh_140939(self):
895895
# gh-140939: MemoryError is raised without leaking
896896
_testcapi = import_helper.import_module('_testcapi')
897-
with self.assertRaises(MemoryError):
897+
with self.assertRaises((MemoryError, OverflowError)):
898898
b = self.type2test(b'%*b')
899899
b % (_testcapi.PY_SSIZE_T_MAX, b'abc')
900900

‎Objects/bytesobject.c‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -747,6 +747,7 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len,
747747
char onechar; /* For byte_converter() */
748748
Py_ssize_t alloc;
749749

750+
const char *start = fmt;
750751
fmt++;
751752
if (*fmt == '%') {
752753
*res++ = '%';
@@ -1108,9 +1109,10 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len,
11081109
alloc = width;
11091110
if (sign != 0 && len == width)
11101111
alloc++;
1111-
/* 2: size preallocated for %s */
1112-
if (alloc > 2) {
1113-
res = PyBytesWriter_GrowAndUpdatePointer(writer, alloc - 2, res);
1112+
/* size preallocated for the format */
1113+
Py_ssize_t prealloc = fmt - start;
1114+
if (alloc > prealloc) {
1115+
res = PyBytesWriter_GrowAndUpdatePointer(writer, alloc - prealloc, res);
11141116
if (res == NULL) {
11151117
Py_XDECREF(temp);
11161118
goto error;

0 commit comments

Comments
 (0)