I'm writing a python-wrapper for C++ algorithm.
- The input of wrapper is a single string or list of ones,
- the output is a single number or list.
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?
Py_XDECREFs? There's reference counting for the objects.Py_XDECREFandPy_DECREFworks only forPyObjects. What should I do If I want to free memoty afterchar*?