Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this PyList_Append(list, Py_BuildValue(...)) leak?

Tags:

Does this leak?:

static PyObject* foo(PyObject* self, PyObject* args){     PyObject* list = PyList_New(0);     for(int i = 0; i < 100; i++)         // leak? does PyList_Append increment ref of the temporary?         PyList_Append(list, Py_BuildValue("i", 42));      return list; } 

Though, I suppose it's better to do this, in any case?:

static PyObject* foo(PyObject* self, PyObject* args){     PyObect* list = PyList_New(100);     for(int i = 0; i < 100; i++)         PyList_SetItem(list, i, Py_BuildValue("i", 42));     return list; } 
like image 897
James Avatar asked Aug 18 '10 13:08

James


1 Answers

PyList_Append does indeed increment the reference counter, so, yes, the first example will leak. PyList_SetItem does not, making it a weird exception.

The second option will be slightly more efficient because the list will be allocated to excatly the right size and Python does have to dynamically resize it as items are appended.

like image 184
Daniel Stutzbach Avatar answered Oct 24 '22 13:10

Daniel Stutzbach