Skip to content

Commit ebf5459

Browse files
[3.14] gh-140939: Fix memory leak in _PyBytes_FormatEx error path (GH-140957) (#141154)
(cherry picked from commit d6c89a2)
1 parent 5d10409 commit ebf5459

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
@@ -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: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -975,8 +975,10 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len,
975975
/* 2: size preallocated for %s */
976976
if (alloc > 2) {
977977
res = _PyBytesWriter_Prepare(&writer, res, alloc - 2);
978-
if (res == NULL)
978+
if (res == NULL) {
979+
Py_XDECREF(temp);
979980
goto error;
981+
}
980982
}
981983
#ifndef NDEBUG
982984
char *before = res;

0 commit comments

Comments
 (0)