简体   繁体   English

Cython功能内存泄漏

[英]Cython function memory leak

I have converted a python function to a cython one. 我已经将python函数转换为cython了。 Now the function works as it is supposed to. 现在,该功能将按预期工作。 But I am getting a lot of memory leak when the main program calls this function multiple times. 但是,当主程序多次调用此函数时,我会遇到很多内存泄漏。 I have freed the memory that I allocated dynamically, but it does not seem to work. 我已经释放了动态分配的内存,但是它似乎不起作用。

What am I doing wrong here? 我在这里做错了什么?

from cpython.mem cimport PyMem_Malloc, PyMem_Free

def longest_common_substring(refWord, stemWord):
cdef:
    int longest, x_longest
    int x, y, k
    Py_ssize_t lengthRefWord
    Py_ssize_t lengthStemWord
    wchar_t *referenceWord = PyUnicode_AsWideCharString(refWord, &lengthRefWord)
    wchar_t *stemmableWord = PyUnicode_AsWideCharString(stemWord, &lengthStemWord)
    int t1 = lengthRefWord+1
    int t2 = lengthStemWord+1
    int **m = <int **> PyMem_Malloc(t1 * sizeof(int *))
    wchar_t tempChar1;
    wchar_t tempChar2;
longest = 0
x_longest = 0

for k in range(t1):
   m[k] = <int *> PyMem_Malloc(t2 * sizeof(int))
for x in range(0, t1):
    for y in range(0, t2):
        m[x][y] = 0

for x in range(1, t1):
    for y in range(1, t2):
       tempChar1 = referenceWord[x - 1]
       tempChar2 = stemmableWord[y - 1]

       if tempChar1 == tempChar2:
           m[x][y] = m[x - 1][y - 1] + 1
           if m[x][y] > longest:
               longest = m[x][y]
               x_longest = x
       else:
           m[x][y] = 0
for k in range(t1):
   PyMem_Free(m[k])
PyMem_Free(m)
return refWord[x_longest - longest: x_longest]

PyUnicode_AsWideCharString allocates memory that you have to free. PyUnicode_AsWideCharString分配您必须释放的内存。 The documentation says 该文件

Returns a buffer allocated by PyMem_Alloc() (use PyMem_Free() to free it) on success. 成功返回一个由PyMem_Alloc()分配的缓冲区(使用PyMem_Free()释放它)。

You get two strings from this function but free neither of them. 您从此函数中获得了两个字符串,但都不释放它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM