tags:

views:

74

answers:

2

I am having an intermittent error causing my Python module to crash, and I'm assuming it's because of a memory error occurring by not getting the refcounts correct in the c code. I have a bit of code that gets a response at a random time from a remote location. Based on the data received, it needs to update a data variable which I should have access to in Python. What's the best way to accomplish this? The following code runs most of the time, and it works correctly when it does, but when it doesn't it crashes Python (bringing up the visual studio debug box). Thanks.

if (event == kResponseEvent) {
    list = PyList_New(0);

    for (i = 0; i < event->count; i++) {
        PyList_Append(list, Py_BuildValue("{s:i, s:s}",
                                          "id", event->id,
                                          "name", event->name));
    }

    PyModule_AddObject(module, "names", list);
}
+1  A: 

PyModule_AddObject() steals a reference. As such, you should not be decrefing list after.

Ignacio Vazquez-Abrams
I've updated the code per your suggestion (that was actually how I originally had it), but it still crashes randomly.
jeffaudio
+1  A: 

PyList_New() can return NULL to indicate an error, which you aren't checking for. Py_BuildValue() can return NULL to indicate an error, which you aren't checking for. PyList_Append() can return -1 to indicate an error, which you're also not checking for. PyList_Append() doesn't steal the reference, so you're leaking the reference to the dict returned by Py_BuildValue(). The latter may be causing you to run out of memory, which can cause Py_BuildValue() or PyList_Append() to fail, and your failure to handle the error can cause a crash.

(Something else can also cause Py_BuildValue() or PyList_Append() to fail, but that's hard to guess at from just this snippet.)

Thomas Wouters
Thanks for the info related to the memory management. Interestingly enough, when I manually called the command to get a response, it never failed, but when I ran it from a for loop to hit it really quickly, it crashed. This leads me to believe that there may be something else wrong in the system that's actually causing the crash. I will look more into this issue.
jeffaudio