C++ and Python 3 memory leak using PyArg_ParseTuple
<p>I'm not a C++ developer so i don't really know what I'm doing. Unfortunately I have to debug the following code but I'm not making any progress.</p>

<pre><code>static PyObject* native_deserialize(PyObject *self, PyObject *args){
  PyObject * pycontent;
  int len;
  PyObject * props  = NULL;
  PyArg_ParseTuple(args, "|SiO", &amp;pycontent, &amp;len, &amp;props);

  RecordParser reader("onet_ser_v0");
  TrackerListener* listener;

  listener = new TrackerListener(props);
  #if PY_MAJOR_VERSION &gt;= 3
      reader.parse((unsigned char*)PyBytes_AsString(pycontent), len, *listener);
  #else
      reader.parse((unsigned char*)PyString_AsString(pycontent), len, *listener);
  #endif
  return listener-&gt;obj;
}
</code></pre>

<p>Here is the python that calls that code:</p>

<pre><code>    clsname, data = pyorient_native.deserialize(content,
                                content.__sizeof__(), self.props)
</code></pre>

<p>This code creates a nasty memory leak. In fact, when I run this code, it kills my memory within 20 minutes.</p>

<p>I looked at the code but can't find the problem in the C++. </p>

<p>How can I prevent rogue C++ code from killing my Python code? Is there a way to flag C++ code from within python to be recycled regardless whether the C++ created a memory leak?</p>

<p>Is there a way I can force the memory to be garbage collected in C++. How can I find the exact leak in C++ by running python?</p>

<p>My biggest issue is understanding Py_XDECREF and Py_XINCREF and the rest of the reference counting macros. I'm reading the docs but obviously I'm missing some context because I can't figure out where and when to use these. I have loads of respect for C++ developers. Their jobs seem unnecessarily difficult :(</p>

<p>It turns out the solution was to Py_XDECREF the reference count for al the created objects. I still don't know exactly how, why and were as many of this still doesn't make sense to me.</p>

<p>I found this page that points out some of the pitfalls of these macros.</p>

<p><a href="https://wingware.com/psupport/python-manual/2.3/ext/node22.html" rel="nofollow">https://wingware.com/psupport/python-manual/2.3/ext/node22.html</a></p>

<p>There is the documentation but that wasn't very helpful.</p>

<p><a href="https://docs.python.org/3/c-api/refcounting.html" rel="nofollow">https://docs.python.org/3/c-api/refcounting.html</a></p>

<p>Maybe someone can share something else that is easier to consume for us non C++ peoplez?</p>

python c++