Skip to content

Commit e3f9b94

Browse files
authored
Update bltinmodule.c
Fix incorrect specialized deallocation of float subclasses in sum() In the complex-number fast path of builtin_sum_impl ( Python/bltinmodule.c ), items are tested with PyFloat_Check() but then released with _Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc) . PyFloat_Check() also matches float subclasses, whereas _PyFloat_ExactDealloc is only valid for exact float objects. As a result, when summing instances of a float subclass into a complex start value, the subclass instances are deallocated as exact floats, bypassing their real tp_dealloc (instance __dict__ , weakref, and GC cleanup). This can leak memory and leave the GC in an inconsistent state. The adjacent float fast path already guards the same specialized dealloc with PyFloat_CheckExact() ; this change brings the complex path in line by using PyFloat_CheckExact() as well. Subclass instances then fall through to the generic PyNumber_Add path with a normal Py_DECREF , preserving numeric behavior while fixing the deallocation. Reproducer: class F(float): pass sum([F(1.0), F(2.0)], 0j) # subclass instances were freed as exact floats Change: in the complex branch of builtin_sum_impl , replace PyFloat_Check(item) with PyFloat_CheckExact(item) (one line).
1 parent 7a468a1 commit e3f9b94

1 file changed

Lines changed: 1 addition & 1 deletion

File tree

Python/bltinmodule.c

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3046,7 +3046,7 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
30463046
return NULL;
30473047
}
30483048
}
3049-
if (PyFloat_Check(item)) {
3049+
if (PyFloat_CheckExact(item)) {
30503050
double value = PyFloat_AS_DOUBLE(item);
30513051
re_sum = cs_add(re_sum, value);
30523052
_Py_DECREF_SPECIALIZED(item, _PyFloat_ExactDealloc);

0 commit comments

Comments
 (0)