[C++-sig] enhancement: Py_DECREF / Py_XDECREF assertion

Stefan Seefeld stefan at seefeld.name
Wed Apr 27 09:14:35 EDT 2016


Hi Willi,

On 26.04.2016 16:19, Wilfried Karel wrote:
> Dear list,
>
> I suggest to insert an assertion before calling Py_DECREF/Py_XDECREF
> which ensures that the reference count before the call is larger than
> zero. Otherwise, this means that a PyObject that has already been
> destroyed is planned to be destroyed a second time - which will not
> happen, as the reference count is of unsigned integer type, and so it
> will become a very large number - but it keeps a PyObject alive that
> references destroyed memory.
>
> I suggest to insert such assertions, because this easily detectable
> programming error is hard to track based on a possibly resulting
> segmentation fault at some later point during program execution (as has
> happened to me). Maybe this would be detected by a debug-build of
> Python, but in my environment, it would be troublesome to link it,
> together with providing possibly needed debug-builds of other Python
> extension packages (e.g. NumPy).
>
> Thus, I suggest to insert
> assert( Py_REFCNT(m_ptr) > 0 );
>
> at the beginning of
> api::object_base::~object_base()
> and
> void decref(T* p)
>
> and to insert
> assert( p == nullptr || Py_REFCNT(python::upcast<PyObject>(p)) > 0 );
> at the beginning of
> void xdecref(T* p)

I'm curious: how do you manage to get non-garbage-collected objects with
zero ref-counts ?

If you can reproduce such cases I think your suggestion is indeed a good
idea. In that case, would you mind submitting a patch / PR (against the
'devel' branch) ? (And seeing you using 'nullptr' above reminds me:
please make sure the code is backward compatible with pre-C++-11).
Please include a test case to demonstrate the failing and fixed behavior.

> Cheers,
> Willi.

Many thanks !

        Stefan

-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list