]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-140939: Fix memory leak in `_PyBytes_FormatEx` error path (GH-140957) ...
authorStan Ulbrych <89152624+StanFromIreland@users.noreply.github.com>
Thu, 6 Nov 2025 16:16:43 +0000 (16:16 +0000)
committerGitHub <noreply@github.com>
Thu, 6 Nov 2025 16:16:43 +0000 (16:16 +0000)
(cherry picked from commit d6c89a2df2c8b7603125883494e9058a88348f66)

Lib/test/test_bytes.py
Misc/NEWS.d/next/Core and Builtins/2025-11-03-17-21-38.gh-issue-140939.FVboAw.rst [new file with mode: 0644]
Objects/bytesobject.c

index a3dec6bf96b7309c3f38a1a5e726a297f619045e..c47fdd8f976d7424cffc421d6fb48afee45878c6 100644 (file)
@@ -769,6 +769,13 @@ class BaseBytesTest:
             with self.assertRaisesRegex(TypeError, msg):
                 operator.mod(format_bytes, value)
 
+    def test_memory_leak_gh_140939(self):
+        # gh-140939: MemoryError is raised without leaking
+        _testcapi = import_helper.import_module('_testcapi')
+        with self.assertRaises(MemoryError):
+            b = self.type2test(b'%*b')
+            b % (_testcapi.PY_SSIZE_T_MAX, b'abc')
+
     def test_imod(self):
         b = self.type2test(b'hello, %b!')
         orig = b
diff --git a/Misc/NEWS.d/next/Core and Builtins/2025-11-03-17-21-38.gh-issue-140939.FVboAw.rst b/Misc/NEWS.d/next/Core and Builtins/2025-11-03-17-21-38.gh-issue-140939.FVboAw.rst
new file mode 100644 (file)
index 0000000..a292176
--- /dev/null
@@ -0,0 +1,2 @@
+Fix memory leak when :class:`bytearray` or :class:`bytes` is formated with the
+``%*b`` format with a large width that results in a :exc:`MemoryError`.
index cebc27f618cba15b2ddc1aa6d6b77f83c34e62d0..d891121589fd3e3998bae5d08fa3d538aec4dee9 100644 (file)
@@ -965,8 +965,10 @@ _PyBytes_FormatEx(const char *format, Py_ssize_t format_len,
             /* 2: size preallocated for %s */
             if (alloc > 2) {
                 res = _PyBytesWriter_Prepare(&writer, res, alloc - 2);
-                if (res == NULL)
+                if (res == NULL) {
+                    Py_XDECREF(temp);
                     goto error;
+                }
             }
 #ifndef NDEBUG
             char *before = res;