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?