Skip to content

Commit 5dc9eb3

Browse files
ZeroIntensitymiss-islington
authored andcommitted
pythongh-140406: Fix memory leak upon __hash__ returning a non-integer (pythonGH-140411)
(cherry picked from commit 71db05a) Co-authored-by: Peter Bierma <[email protected]>
1 parent 98d4c21 commit 5dc9eb3

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
@@ -1183,6 +1183,16 @@ def __hash__(self):
11831183
return self
11841184
self.assertEqual(hash(Z(42)), hash(42))
11851185

1186+
def test_invalid_hash_typeerror(self):
1187+
# GH-140406: The returned object from __hash__() would leak if it
1188+
# wasn't an integer.
1189+
class A:
1190+
def __hash__(self):
1191+
return 1.0
1192+
1193+
with self.assertRaises(TypeError):
1194+
hash(A())
1195+
11861196
def test_hex(self):
11871197
self.assertEqual(hex(16), '0x10')
11881198
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
@@ -10195,6 +10195,7 @@ slot_tp_hash(PyObject *self)
1019510195
return PyObject_HashNotImplemented(self);
1019610196
}
1019710197
if (!PyLong_Check(res)) {
10198+
Py_DECREF(res);
1019810199
PyErr_SetString(PyExc_TypeError,
1019910200
"__hash__ method should return an integer");
1020010201
return -1;

0 commit comments

Comments
 (0)