c++算法的python包装器内存泄漏

Memory leaks in python wrapper for C++ algorithm

本文关键字:内存 泄漏 包装 python 算法 c++      更新时间:2023-10-16

我正在为c++算法编写一个python包装器。

  • 包装器的输入是一个字符串或字符串列表,
  • 输出为单个数字或列表。

包装器的主要功能如下:

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;
}

repeating_count::count()的实现无关紧要。

在这段代码中是否存在内存泄漏 ?我怎样才能修好它们呢?

我知道,PyArg_Parse()PyArg_ParseTuple()str动态分配内存。但是,如果解析失败,我如何释放这些内存呢?我不知道如何分配这个内存,因此我不能释放它。

  • free(str)
  • delete(str)
  • delete str
  • delete[] str

不工作。

你能帮我吗?

From the docs:

不能为字符串本身提供存储空间;指针指向现有字符串存储在字符指针变量中您经过的地址

https://docs.python.org/2.0/ext/parseTuple.html

你得到一个指向python托管字符串的指针,你不负责释放内存