Trouble with ref counts in C extension
Mark Hammond
MarkH at ActiveState.com
Mon Dec 3 02:09:31 EST 2001
Michel Pelletier wrote:
> static PyObject *
> FiclVM_pop(FiclVMObject *self, PyObject *args)
> {
> CELL c;
> PyObject *ob;
>
> if (!PyArg_ParseTuple(args, ":pop"))
> return NULL;
> if (!stackDepth(self->ficl_vm->pStack))
> return NULL; // handle better...
>
> c = vmPop(self->ficl_vm);
>
> ob = (PyObject*)(c.p);
> Py_DECREF(ob);
The DECREF is not needed here.
You need one DECREF to remove the reference that was consumed by the
stack - but you then need one INCREF for the result of the function.
The end result means that the function is reference neutral.
FWIW:
> if (!stackDepth(self->ficl_vm->pStack))
> return NULL; // handle better...
Should be something like:
if (!stackDepth(self->ficl_vm->pStack)) {
PyErr_SetString(PyExc_ValueError, "Out of stack items");
return NULL;
}
(or any other exception value you choose)
Mark.
More information about the Python-list
mailing list