Reputation: 3157
I'm writing a python-wrapper for C++ algorithm.
The main function of this wrapper is below:
PyObject* count_rep_list(PyObject *mod, PyObject *args){
PyObject *inputList = PyTuple_GetItem(args, 0);
PyObject *outputList = PyList_New(0);
char* str;
if(PyList_Check(inputList)) {
for (size_t i = 0; i < PyList_Size(inputList); ++i) {
PyObject *list_item = PyList_GetItem(inputList, i);
if (!PyArg_Parse(list_item, "s", &str)) {
Py_XDECREF(list_item);
Py_XDECREF(inputList);
Py_XDECREF(outputList);
return NULL;
}
Py_DECREF(list_item);
PyList_Append(outputList, PyLong_FromSize_t(repeating_count::count(string(str))));
}
}
else if(!PyArg_ParseTuple(args, "s", &str)){
Py_XDECREF(inputList);
Py_XDECREF(outputList);
return NULL;
}
else {
PyList_Append(outputList, PyLong_FromSize_t(repeating_count::count(string(str))));
}
return outputList;
}
The realization of the repeating_count::count()
doesn't matter.
Are there memory leaks in this code? How can I fix them?
I know, that PyArg_Parse()
and PyArg_ParseTuple()
allocate memory for str
dynamically. But how can I free this memory if parsing failed? I don't know how this memory was allocated, therefore I can't free it. So,
free(str)
,delete(str)
,delete str
,delete[] str
aren't working.
Can you help me?
Upvotes: 3
Views: 251
Reputation: 504
From the docs:
You must not provide storage for the string itself; a pointer to an existing string is stored into the character pointer variable whose address you pass.
https://docs.python.org/2.0/ext/parseTuple.html
You're getting a pointer to the python managed string, you aren't responsible for freeing the memory.
Upvotes: 1