Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leaks in python wrapper for C++ algorithm

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?

like image 765
VeLKerr Avatar asked Mar 27 '26 07:03

VeLKerr


1 Answers

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.

like image 200
georgeofallages Avatar answered Mar 28 '26 19:03

georgeofallages



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!