3

I called in Python one C function named decrypt, and decrypt returns one malloced memory buffer.

The code is as below:

 sl = ctypes.cdll.LoadLibrary('some_crypto.so')
 sl.decrypt.argtypes = [ctypes.c_char_p]
 sl.decrypt.restype = ctypes.c_char_p
 ret = sl.decrypt(ctypes.c_char_p(ciphertext))

At this stage, underlying C function decrypt malloced one buffer and returned to Python as ret.

Do I need to release the memory of ret variable to avoid memory leak ?

If yes, how can I release the underlying memory buffer?

More details added according to comments. This case is different from How to free memory allocated by external C libraries interfacing with Cython module where the memory is ultimately returned to a Python process?, since no Cython is used here.

And as suggested here Memory leaks in Python when using an external C DLL, I use convert_and_free_char_p as the restype of C function decrypt, but still found memory leak through htop.

def convert_and_free_char_p(char_p):
  if char_p == 0:
      return None
  try:
      return ctypes.c_char_p(char_p).value
  finally:
      libc.free(char_p)

sl = ctypes.cdll.LoadLibrary('some_crypto.so')
sl.decrypt.argtypes = [ctypes.c_char_p]
sl.decrypt.restype = ctypes.convert_and_free_char_p
for i in range(0, 10000000000000):
    ret = sl.decrypt(ctypes.c_char_p(ciphertext))

VIRT/RES column of this script in htop kept insreasing, indicating memory leak..

How comes the free not working properly?

FaceBro
  • 787
  • 2
  • 13
  • 29
  • 1
    Possible duplicate of [How to free memory allocated by external C libraries interfacing with Cython module where the memory is ultimately returned to a Python process?](https://stackoverflow.com/questions/56135191/how-to-free-memory-allocated-by-external-c-libraries-interfacing-with-cython-mod) – gstukelj Nov 24 '19 at 13:46
  • Also see https://stackoverflow.com/questions/47080411/do-i-need-to-free-memory-returned-from-a-c-function-called-via-cffi and https://stackoverflow.com/questions/25758048/memory-leaks-in-python-when-using-an-external-c-dll – gstukelj Nov 24 '19 at 13:47

0 Answers0