From cc3acde9bbf476a5a6e57423fb7c21f94d5f0a7a Mon Sep 17 00:00:00 2001 From: Luc Grosheintz Date: Thu, 21 Nov 2024 11:42:47 +0100 Subject: [PATCH] Fix leak in `object_to_double_`. (#3235) The fact: * `nrnpy_ho2po` seems to return a "new reference". * `PyFloat_AsDouble` doesn't steal [1]. Therefore, the previous version had: * A local reference count of `+1` after `ho2po`. * A local reference count of `+2` after `INCREF`. * The `PyFloat_AsDouble` doesn't change the reference count. * A local reference count of `+1` after `DECREF`. Leaving one INCREF that we can't pair up with a DECREF. The proposed version immediately takes ownership of the new reference returned by `nrnpy_ho2po`. [1]: https://docs.python.org/3/c-api/float.html#c.PyFloat_AsDouble --- src/nrnpython/nrnpy_hoc.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/nrnpython/nrnpy_hoc.cpp b/src/nrnpython/nrnpy_hoc.cpp index 841d29314b..a5baabfd55 100644 --- a/src/nrnpython/nrnpy_hoc.cpp +++ b/src/nrnpython/nrnpy_hoc.cpp @@ -2652,10 +2652,8 @@ extern "C" NRN_EXPORT int nrnpy_set_gui_callback(PyObject* new_gui_callback) { } static double object_to_double_(Object* obj) { - PyObject* const pyobj = nrnpy_ho2po(obj); - Py_INCREF(pyobj); - const double result = PyFloat_AsDouble(pyobj); - Py_DECREF(pyobj); + auto pyobj = nb::steal(nrnpy_ho2po(obj)); + const double result = PyFloat_AsDouble(pyobj.ptr()); return result; }