ctypes & allocated memory
Miki Tebeka
miki.tebeka at gmail.com
Mon Jun 8 01:34:05 EDT 2020
Hi,
> But the problem is that by specifying the type as ctypes.c_char_p,
> ctypes will hide that pointer from you and return a Python object
> instead. I'm not sure how ctypes is doing it under the hood, but I
> suspect ctypes is doing it's own strdup of the string on conversion, and
> managing that memory, but the original pointer ends up being lost and
> leaking memory.
Yes, the problem with my code I posted is that resource.getrusage report the Python allocated memory. Once I've changed to psutil.Process().memory_info().rss I see the memory leak. The code now looks like:
---
...
strdup.restype = ctypes.c_void_p
free = libc.free
free.argtypes = [ctypes.c_void_p]
...
for _ in range(n):
o = strdup(data)
s = ctypes.string_at(o).decode('utf-8')
free(o)
---
This seems to fix the leak.
Thanks
More information about the Python-list
mailing list