Skip to content

Commit f1a9372

Browse files
[3.13] gh-140939: Fix memory leak in _PyBytes_FormatEx error path (GH-140957) (#141155)
(cherry picked from commit d6c89a2)
1 parent 908695b commit f1a9372

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

Lib/test/test_bytes.py

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

772+
def test_memory_leak_gh_140939(self):
773+
# gh-140939: MemoryError is raised without leaking
774+
_testcapi = import_helper.import_module('_testcapi')
775+
with self.assertRaises(MemoryError):
776+
b = self.type2test(b'%*b')
777+
b % (_testcapi.PY_SSIZE_T_MAX, b'abc')
778+
772779
def test_imod(self):
773780
b = self.type2test(b'hello, %b!')
774781
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: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -965,8 +965,10 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len,
965965
/* 2: size preallocated for %s */
966966
if (alloc > 2) {
967967
res = _PyBytesWriter_Prepare(&writer, res, alloc - 2);
968-
if (res == NULL)
968+
if (res == NULL) {
969+
Py_XDECREF(temp);
969970
goto error;
971+
}
970972
}
971973
#ifndef NDEBUG
972974
char *before = res;

0 commit comments

Comments
 (0)