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

Wilfried Karel wilfried.karel at geo.tuwien.ac.at
Tue Apr 26 16:19:09 EDT 2016


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)

Cheers,
Willi.
-- 
                        _____ _____ _____  Technische Universität Wien
   DI Wilfried Karel   /____// ___//    / Dept. of Geodesy & Geoinform.
  wilfried.karel@     // __ / /__ / // / Research Groups Photogrammetry
 geo.tuwien.ac.at    //__/// /__ / // /   & Remote Sensing
+43 1 58801 12244   /____//____//____/ Gusshausstr. 27-29, A-1040 Wien


More information about the Cplusplus-sig mailing list