[英]Memory leaks in python wrapper for C++ algorithm
I'm writing a python-wrapper for C++ algorithm. 我正在为C ++算法编写一个python-wrapper。
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. repeating_count::count()
实现无关紧要。
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. 我知道,
PyArg_Parse()
和PyArg_ParseTuple()
动态地为str
分配内存。 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)
, free(str)
, delete(str)
, delete(str)
, delete str
, delete str
, delete[] str
aren't working. 不工作。
Can you help me? 你能帮助我吗?
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 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. 你得到一个指向python托管字符串的指针,你不负责释放内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.