Search code examples
pythoncsegmentation-faultpython-c-api

Python C-Extension segfaults when accessing through tp_getset


I'm trying to write a C-Extension for python. What I'd like to write is a ModPolynomial class which represents a polynomial on (Z/nZ)[x]/x^r-1[even though you may answer to my question without knowing anything of such polynomials].

I've written some code, which seems to work. Basically I just store three PyObject* in my ModPoly structure. Now I'd like to add the storage for the coefficients of the polynomial.

Since I want the coefficients to be read-only, I'd like to add a getter/setter pair of functions through PyGetSetDef. But when I access the getter from python(e.g print pol.coefficients) I receive a Segmentation Fault.

The original code, without the "coefficients" can be found here. The code with the coefficients is here.

I hope someone of you can tell me where I'm doing wrong here. By the way, also comments on the code are welcome. This is my first extension and I know that I'm probably doing things quite badly.

As ecatmur says in the comments PyVarObject store a certain number of "slots" at the end of the struct. So I've decided to avoid them.

The relevant code is:

typedef struct {
    PyObject_HEAD
    /* Type specific fields */

    Py_ssize_t ob_size;
    PyObject **ob_item;
    Py_ssize_t allocated;

    PyObject *r_modulus;
    PyObject *n_modulus;
    PyObject *degree;
} ModPoly;



static PyObject *
ModPoly_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    ModPoly *self;

    self = (ModPoly *)type->tp_alloc(type, 0);
    if (self != NULL) {
        [...]

        self->ob_size = 0;
        self->ob_item = NULL;
        self->allocated = 0;
    }

    return (PyObject *)self;
}


static int
ModPoly_init(ModPoly *self, PyObject *args, PyObject *kwds)
{
    PyObject *r_modulus=NULL, *n_modulus=NULL, *coefs=NULL, *tmp;
    PyObject **tmp_ar;

    static char *kwlist[] = {"r_modulus", "n_modulus", "coefficients", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO|O", kwlist,
                                     &r_modulus, &n_modulus, &coefs))
        return -1;

    [...]

    // The polynomial defaults to "x", so the coefficients should be [0, 1].
    tmp_ar = (PyObject **)malloc(2 * sizeof(PyObject*));
    if (tmp_ar == NULL) {
        Py_DECREF(self->r_modulus);
        Py_DECREF(self->n_modulus);
        Py_DECREF(self->degree);
        return -1;
    }

    tmp_ar[0] = PyInt_FromLong(0);
    if (tmp_ar[0] != NULL) {
        tmp_ar[1] = PyInt_FromLong(1);
    }

    if (tmp_ar[0] == NULL || tmp_ar[0] == NULL) {
        Py_DECREF(self->r_modulus);
        Py_DECREF(self->n_modulus);
        Py_DECREF(self->degree);
        Py_XDECREF(tmp_ar[0]);
        Py_XDECREF(tmp_ar[1]);
        free(tmp_ar);
        return -1;
    }

    self->ob_size = 2;
    self->allocated = 2;

    return 0;
}

[...]

static PyObject *
ModPoly_getcoefs(ModPoly *self, void *closure)
{
    printf("here"); // "here" is never printed
    PyTupleObject *res=(PyTupleObject*)PyTuple_New(self->ob_size);
    Py_ssize_t i;
    PyObject *tmp;

    if (res == NULL)
        return NULL;

    for (i=0; i < self->ob_size; i++) {
        tmp = self->ob_item[i];
        Py_INCREF(tmp);
        PyTuple_SET_ITEM(res, i, tmp);
    }
    return (PyObject *)res;
}

static PyObject *
ModPoly_setcoefs(ModPoly *self, PyObject *value, void* closure)
{
    PyErr_SetString(PyExc_AttributeError,
                    "Cannot set the coefficients of a polynomial.");
    return NULL;
}

[...]

static PyGetSetDef ModPoly_getsetters[] = {
  {"coefficients",
      (getter)ModPoly_getcoefs, (setter)ModPoly_setcoefs,
    "The polynomial coefficients.", NULL},
  {NULL, 0, 0, NULL, NULL}  
};


static PyTypeObject ModPolyType = {
    PyObject_HEAD_INIT(NULL)
        0,                                                                      /* ob_size        */
    [...]
    ModPoly_members,                                        /* tp_members */
    ModPoly_getsetters,                                     /* tp_getset */
    0,                                                      /* tp_base */
    [...]
};

[...]

edit

I tried to reimplement the getter instruction by instruction, and I understood what I wasn't doing. In the ModPoly_init function I create the tmp_ar where I store the coefficients, but I do not assign it to self->ob_item.

-facepalm-


Solution

  • You only seem to be assigning to ModPoly.ob_item in ModPoly_new() (setting it to NULL).

    ModPoly_getcoefs() then dereferences the null pointer, which would give you your segfault. It looks like you intended to assign to ob_item in ModPoly_init(), but don't actually get around to doing so.