I have a reference in C to a Python list of dictionaries. I am writing a function to calculate the dot product between two members of the list:
PyObject *handle; // reference to a list of dictionaries
virtual float dot_product () (unsigned i, unsigned j) const {
// dot product of handle[i] and handle[j]
PyObject *a = (PyObject*)PyList_GetItem(handle, (Py_ssize_t)i);
PyObject *b = (PyObject*)PyList_GetItem(handle, (Py_ssize_t)j);
PyObject *key, *a_value;
Py_ssize_t pos = 0;
double dot_product = 0;
while (PyDict_Next(a, &pos, &key, &a_value)) {
PyObject* b_value = PyDict_GetItem(b, key);
if (b_value != NULL){
dot_product += PyFloat_AsDouble(a_value) * PyFloat_AsDouble(b_value);
}
}
return dot_product;
}
This results in a segmentation fault. Using gdb to debug, it appears that the segmentation fault is being caused by PyDict_GetItem(b, key). This makes me suspect there's something wrong with my reference counts.
After reading the documentation on Reference Counts, it seems that all of the references in the above code are borrowed, so I assumed there was no need to use Py_INCREF or Py_DECREF...but I could easily be wrong. Is there a place in the above code that I need to use Py_INCREF or Py_DECREF?
Edit: I should note that I have already done checks to make sure a and b are not null, and also checks to ensure i and j do not exceed the size of the list. I removed these checks from the code in my question to keep it simpler. –