2

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?

1
  • You can use Valgrind to debug some segmentation fault issues. Commented Aug 18, 2014 at 14:04

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Well, I added NULL ckeck on PyList_GetItem() but still the same segmentation fault appears.
again, don't Py_DECREF(item). it's a borrowed reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.