Skip to content

Commit 6a88b06

Browse files
ZeroIntensityStanFromIreland
authored andcommitted
pythongh-140406: Fix memory leak upon __hash__ returning a non-integer (pythonGH-140411)
1 parent 51bea22 commit 6a88b06

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

1187+
def test_invalid_hash_typeerror(self):
1188+
# GH-140406: The returned object from __hash__() would leak if it
1189+
# wasn't an integer.
1190+
class A:
1191+
def __hash__(self):
1192+
return 1.0
1193+
1194+
with self.assertRaises(TypeError):
1195+
hash(A())
1196+
11871197
def test_hex(self):
11881198
self.assertEqual(hex(16), '0x10')
11891199
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
@@ -10569,6 +10569,7 @@ slot_tp_hash(PyObject *self)
1056910569
return PyObject_HashNotImplemented(self);
1057010570
}
1057110571
if (!PyLong_Check(res)) {
10572+
Py_DECREF(res);
1057210573
PyErr_SetString(PyExc_TypeError,
1057310574
"__hash__ method should return an integer");
1057410575
return -1;

0 commit comments

Comments
 (0)