3

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?

2
  • Do you see those Py_XDECREFs? There's reference counting for the objects. Commented Sep 15, 2015 at 18:49
  • @KarolyHorvath, yes, but Py_XDECREF and Py_DECREF works only for PyObjects. What should I do If I want to free memoty after char*? Commented Sep 15, 2015 at 18:55

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.