selfbg
selfbg

Reputation: 315

Python C-API segmentation fault

I have this code:

static PyObject* py_write(PyObject *self, PyObject* args){

    PyObject *tx_list;
    PyObject *item = 0;
    uint8_t tx_len = 0;

    /* Parse arguments */
    if(!PyArg_ParseTuple(args, "O!", &PyList_Type, &tx_list)){
        return NULL;
    }

    /* Get length of list */
    tx_len = PyList_Size(tx_list);

    /* Allocate memory for output buffer */
    uint8_t *tx_buffer = (uint8_t *)malloc(tx_len * sizeof(uint8_t));
    memset(tx_buffer, 0, sizeof(uint8_t));

    /* Populate output buffer */
    int i;
    for(i = 0; i < tx_len; i++){
        item = PyList_GetItem(tx_list, i);
        tx_buffer[i] = (uint8_t)PyInt_AsLong(item);
    }

    /* Send data */
    if(spi_write(fd, tx_buffer, tx_len) < 0){
        return PyErr_SetFromErrno(PyExc_IOError);
    }

    /* Do cleanup */
    free(tx_buffer);
    Py_DECREF(item);
    Py_DECREF(tx_list);

    Py_RETURN_NONE;
}

When I call once this method there is no problem. But on ~2000 I get segmentation fault. I guess that there is something wrong with my reference count. Can someone give me a hand or tell my some method for debugging?

Upvotes: 2

Views: 656

Answers (1)

Woodrow Douglass
Woodrow Douglass

Reputation: 2655

PyList_GetItem returns a borrowed reference, you don't need to Py_DECREF item. Also, when calling Python C-Api calls, NULL is returned if there's an exception. Check for NULL from PyList_GetItem.

Upvotes: 2

Related Questions