Skip to content

Commit 649986b

Browse files
committed
pythongh-140406: Fix memory leak upon __hash__ returning a non-integer (pythonGH-140411)
(cherry picked from commit 71db05a)
1 parent df35beb commit 649986b

File tree

3 files changed

+13
-0
lines changed

3 files changed

+13
-0
lines changed

Lib/test/test_builtin.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1094,6 +1094,16 @@ def __hash__(self):
10941094
return self
10951095
self.assertEqual(hash(Z(42)), hash(42))
10961096

1097+
def test_invalid_hash_typeerror(self):
1098+
# GH-140406: The returned object from __hash__() would leak if it
1099+
# wasn't an integer.
1100+
class A:
1101+
def __hash__(self):
1102+
return 1.0
1103+
1104+
with self.assertRaises(TypeError):
1105+
hash(A())
1106+
10971107
def test_hex(self):
10981108
self.assertEqual(hex(16), '0x10')
10991109
self.assertEqual(hex(-16), '-0x10')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix memory leak when an object's :meth:`~object.__hash__` method returns an
2+
object that isn't an :class:`int`.

Objects/typeobject.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9530,6 +9530,7 @@ slot_tp_hash(PyObject *self)
95309530
return -1;
95319531

95329532
if (!PyLong_Check(res)) {
9533+
Py_DECREF(res);
95339534
PyErr_SetString(PyExc_TypeError,
95349535
"__hash__ method should return an integer");
95359536
return -1;

0 commit comments

Comments
 (0)