]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.14] gh-140406: Fix memory leak upon `__hash__` returning a non-integer (GH-140411...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Tue, 21 Oct 2025 12:35:31 +0000 (14:35 +0200)
committerGitHub <noreply@github.com>
Tue, 21 Oct 2025 12:35:31 +0000 (12:35 +0000)
gh-140406: Fix memory leak upon `__hash__` returning a non-integer (GH-140411)
(cherry picked from commit 71db05a12d9953a96f809d84b4d0d452a464e431)

Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
Lib/test/test_builtin.py
Misc/NEWS.d/next/Core_and_Builtins/2025-10-21-06-51-50.gh-issue-140406.0gJs8M.rst [new file with mode: 0644]
Objects/typeobject.c

index 8830641f0abdc79048665f2308d7fa7a8a81d32f..413429f51096c51333458d6241d0ed6129e06cbb 100644 (file)
@@ -1183,6 +1183,16 @@ class BuiltinTest(ComplexesAreIdenticalMixin, unittest.TestCase):
                 return self
         self.assertEqual(hash(Z(42)), hash(42))
 
+    def test_invalid_hash_typeerror(self):
+        # GH-140406: The returned object from __hash__() would leak if it
+        # wasn't an integer.
+        class A:
+            def __hash__(self):
+                return 1.0
+
+        with self.assertRaises(TypeError):
+            hash(A())
+
     def test_hex(self):
         self.assertEqual(hex(16), '0x10')
         self.assertEqual(hex(-16), '-0x10')
diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2025-10-21-06-51-50.gh-issue-140406.0gJs8M.rst b/Misc/NEWS.d/next/Core_and_Builtins/2025-10-21-06-51-50.gh-issue-140406.0gJs8M.rst
new file mode 100644 (file)
index 0000000..3506ba4
--- /dev/null
@@ -0,0 +1,2 @@
+Fix memory leak when an object's :meth:`~object.__hash__` method returns an
+object that isn't an :class:`int`.
index 28451fee7ec10f4a1ab756ab29240d05ca8d1ab3..954547eb4fb7b06043b26f44b54ab7aa09601879 100644 (file)
@@ -10195,6 +10195,7 @@ slot_tp_hash(PyObject *self)
         return PyObject_HashNotImplemented(self);
     }
     if (!PyLong_Check(res)) {
+        Py_DECREF(res);
         PyErr_SetString(PyExc_TypeError,
                         "__hash__ method should return an integer");
         return -1;