Freeing a PyTuple object

1.3k views Asked by At

What is the proper way to free a PyTuple object using the Python C-API?

I know that tuples are somewhat special when it comes to the reference counting semantics, since PyTuple_SetItem "steals" the reference to the inserted element. I also know that decrementing the reference of a tuple object decrements the reference count of all the elements in the tuple.

With this in mind, I would think it should be safe to say:

#include <Python.h>
#include <stdio.h>

int main()
{
    PyObject* tup = PyTuple_New(1);
    PyTuple_SetItem(tup, 0, PyLong_FromLong(100L));

    printf("Ref Count: %d\n", tup->ob_refcnt);
    Py_DECREF(tup);
}

But the last line causes a Segmentation Fault, when I decrement the tuple reference count. I don't understand why this happens. Right before the call to Py_DECREF the reference count is 1, so what's the issue here?

1

There are 1 answers

1
Tomek Szpakowicz On

Add call to Py_Initialize(); at the beginning of main and try again.