memory leak
Gabriel Genellina
gagsl-py at yahoo.com.ar
Sun Jan 28 20:03:46 EST 2007
At Wednesday 24/1/2007 22:06, john g wrote:
>i have a memory leak issue with extension function that im working
>on. it reads data from a binary file into a stl vector then creates
>a new list to pass back to the python interface. the function works
>the first 1021 times but then gives a segmentation fault (core
>dumped). heres the business part of the code:
>
>
>//read data
> vector<float> data;
> float temp;
>
>
> for(int x=0;x<np*2;x++)
> {
> fread(&temp,sizeof(float),1,datfil);
> data.push_back(temp);
> }
>
>
> //convert vector to list
> PyObject *newlist = PyList_New(np*2);
> PyList_SetItem(newlist, 0,PyFloat_FromDouble(data[0]));
> for(int x=0;x<np*2;x++)
> {
> PyList_SetItem(newlist, x,PyFloat_FromDouble(data[x]));
> }
>
>
>
>
>
>
> //send back list
> return newlist;
You have to check for possible errors. And you don't need to build
the C++ vector, just use PyList_SET_ITEM on each value as you read
it. (_SET_ITEM because it's a new, empty, list). This is how I'd do
that (untested):
float temp;
PyObject *newlist;
newlist = PyList_New(np*2);
if (newlist == NULL)
return NULL;
for(int x=0;x<np*2;x++)
{
fread(&temp,sizeof(float),1,datfil);
// fread could fail, you should do some error handling here,
search the python
// sources for examples; possibly setting an exception and "goto err"
PyList_SET_ITEM(newlist, x, PyFloat_FromDouble(temp));
}
if (PyErr_Occurred()) {
goto err;
}
return newlist;
err:
Py_DECREF(newlist);
return NULL;
--
Gabriel Genellina
Softlab SRL
__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas
More information about the Python-list
mailing list