PyObject_CallObject code dump after calling 4 times

Fredrik Lundh fredrik at pythonware.com
Thu Jan 3 07:00:08 EST 2008


grbgooglefan wrote:

> I have a following C++ code which uses PyObject_CallObject to evaluate
> expressions dynamically. This code sets the input parameters for the
> function also dynamically. After calling this function 4 times (with
> these shown values), PyObject_CallObject  causes application to crash
> in frame_dealloc.
> 1) Can some one please help me understand why is this crash happening
> in frame_dealloc & how to solve it?
> 2) Is there anything wrong I am doing about incrementing or
> decrementing the reference counts of the object passed to
> PyObject_CallObject?

if something crashes after a while, it's almost always a reference count 
error.

>        default:
>          printf("Unknown data type [%d] for %s\n",ndtyp,pEvalFunc-
>> pExprVarsArray[nCtr].szVarName);
> }

what's val set to if this happens?

> if(!val){
>    ret = -1;
>    printf("Failed to convert %d %s to PyObject\n",ndtyp,pEvalFunc-
>> pExprVarsArray[nCtr].szVarName); fflush(stdout);
>    Py_XDECREF(pTuple);
>    break;
> }
>   PyTuple_SetItem(pTuple, nCtr, val);
>   Py_XDECREF(val);
> }

PyTuple_SetItem "steals" a reference

     http://docs.python.org/api/refcountDetails.html

so you shouldn't DECREF val yourself.

> // all variables are set, call Python function
> Py_XINCREF(pTuple);

this isn't necessary, and will (most likely) result in a leak.

>   PyObject *pResult = PyObject_CallObject(pEvalFunc-
>> pPyEvalFunction,pTuple);
> Py_XDECREF(pTuple);
> 
> if(PyErr_Occurred()){
>  PyErr_Print();
> } else {
>       char* plevel = NULL;
>       if(NULL != (plevel = PyString_AsString(pResult))){
>         ret = 0;
>         sprintf(szEvalResult,"%s",plevel);

shouldn't you check the size of plevel here, before copying it to 
szEvalResult?  (and what's wrong with using strcpy to do the copy,
btw?)

</F>




More information about the Python-list mailing list