Skip to content

Commit d6c89a2

Browse files
gh-140939: Fix memory leak in _PyBytes_FormatEx error path (#140957)
1 parent 9037a38 commit d6c89a2

File tree

3 files changed

+10
-0
lines changed

3 files changed

+10
-0
lines changed

Lib/test/test_bytes.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -802,6 +802,13 @@ def __int__(self):
802802
with self.assertRaisesRegex(TypeError, msg):
803803
operator.mod(format_bytes, value)
804804

805+
def test_memory_leak_gh_140939(self):
806+
# gh-140939: MemoryError is raised without leaking
807+
_testcapi = import_helper.import_module('_testcapi')
808+
with self.assertRaises(MemoryError):
809+
b = self.type2test(b'%*b')
810+
b % (_testcapi.PY_SSIZE_T_MAX, b'abc')
811+
805812
def test_imod(self):
806813
b = self.type2test(b'hello, %b!')
807814
orig = b
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix memory leak when :class:`bytearray` or :class:`bytes` is formated with the
2+
``%*b`` format with a large width that results in a :exc:`MemoryError`.

Objects/bytesobject.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -985,6 +985,7 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len,
985985
if (alloc > 2) {
986986
res = PyBytesWriter_GrowAndUpdatePointer(writer, alloc - 2, res);
987987
if (res == NULL) {
988+
Py_XDECREF(temp);
988989
goto error;
989990
}
990991
}

0 commit comments

Comments
 (0)