Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: CTypes memory leak with Structure

Does Python ctypes have a known memory leak? I am working on a Python script having code like the below snippet, using ctypes, that for some reason is causing a memory leak. The "while True" in this example is to test for the leak caused by calling the function. It is being run on Windows with Python 2.5.4:

import ctypes
def hi():
    class c1(ctypes.Structure):
            _fields_=[('f1',ctypes.c_uint8)]
    class c2(ctypes.Structure):
            _fields_=[('g1',c1*2)]

while True:
    test=hi()

The leak can be tested using ProcessExplorer -- as it keeps looping, Python keeps taking up more and more memory. It seems to require having two Structure subclasses where one of the classes has a "multiple" of the other one (using the * operator), but I'm not sure if the condition is more basic than that. Even if del test is added in the loop, it still leaks memory.

Any ideas on what might be causing this?

Edit: Because someone suggested it might not have garbage-collected yet, here is an edited version that does garbage-collect but still appears to leak memory:

import gc
import ctypes
def hi():
    class c1(ctypes.Structure):
            _fields_=[('f1',ctypes.c_uint8)]
    class c2(ctypes.Structure):
            _fields_=[('g1',c1*2)]

while True:
    test=hi()
    test2=gc.collect()
like image 494
user553702 Avatar asked Aug 13 '26 21:08

user553702


1 Answers

That's not a memory leak, that just means the garbage collector hasn't run yet. And even if the garbage collector does run, odds are good that there's some kind of memory pooling going on.

ProcessExplorer isn't a good debugging tool, especially for memory.

like image 81
Chris Eberle Avatar answered Aug 15 '26 12:08

Chris Eberle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!