https://github.com/python/cpython/commit/0fdae5f590b9322256a37b53176abb6f2e1705f5
commit: 0fdae5f590b9322256a37b53176abb6f2e1705f5
branch: 3.14
author: Miss Islington (bot) <[email protected]>
committer: ZeroIntensity <[email protected]>
date: 2025-10-23T10:20:16Z
summary:

[3.14] gh-140474: Fix memory leak in `array.array` (GH-140478) (GH-140498)

gh-140474: Fix memory leak in `array.array` (GH-140478)
(cherry picked from commit aa9d0a61d5c48717454f36351f0aabe4cc532de5)

Co-authored-by: Stan Ulbrych <[email protected]>

files:
A Misc/NEWS.d/next/Library/2025-10-22-20-52-13.gh-issue-140474.xIWlip.rst
M Lib/test/test_array.py
M Modules/arraymodule.c

diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py
index 58ea89c4fac833..83b3c978da3581 100755
--- a/Lib/test/test_array.py
+++ b/Lib/test/test_array.py
@@ -1255,6 +1255,14 @@ def test_typecode_u_deprecation(self):
         with self.assertWarns(DeprecationWarning):
             array.array("u")
 
+    def test_empty_string_mem_leak_gh140474(self):
+        with warnings.catch_warnings():
+            warnings.simplefilter('ignore', DeprecationWarning)
+            for _ in range(1000):
+                a = array.array('u', '')
+                self.assertEqual(len(a), 0)
+                self.assertEqual(a.typecode, 'u')
+
 
 class UCS4Test(UnicodeTest):
     typecode = 'w'
diff --git 
a/Misc/NEWS.d/next/Library/2025-10-22-20-52-13.gh-issue-140474.xIWlip.rst 
b/Misc/NEWS.d/next/Library/2025-10-22-20-52-13.gh-issue-140474.xIWlip.rst
new file mode 100644
index 00000000000000..aca4e68b1e5e49
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2025-10-22-20-52-13.gh-issue-140474.xIWlip.rst
@@ -0,0 +1,2 @@
+Fix memory leak in :class:`array.array` when creating arrays from an empty
+:class:`str` and the ``u`` type code.
diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c
index 5d07de2fba9526..39d505c02596b8 100644
--- a/Modules/arraymodule.c
+++ b/Modules/arraymodule.c
@@ -2838,6 +2838,9 @@ array_new(PyTypeObject *type, PyObject *args, PyObject 
*kwds)
                         Py_SET_SIZE(self, n);
                         self->allocated = n;
                     }
+                    else {
+                        PyMem_Free(ustr);
+                    }
                 }
                 else { // c == 'w'
                     Py_ssize_t n = PyUnicode_GET_LENGTH(initial);

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to