[issue41977] ctypes array inside structure requires explicit garbage collection

2020-10-12 Thread Filipe Laíns

Change by Filipe Laíns :


--
nosy: +FFY00

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue41977] ctypes array inside structure requires explicit garbage collection

2020-10-08 Thread Maximilian Pichler


New submission from Maximilian Pichler :

If we initialize a `Structure` with two fields as...
```python
s = S()
s.x = (c_int * 10**8)()
s.y = s.x
```
...and then delete it with ```del s```, the memory allocated for the array is 
not freed until `gc.collect()` is called.

If instead we initalize `s` as...
```python
s = S()
a = (c_int * 10**8)()
s.x = a
s.y = a
del a
```
the memory is freed immediately, no need to garbage collect.

This behaviour seems inconsistent.

Also, if instead of `del s` we do...
```python
s.x = None
s.y = None
```
...memory usage remains high even after garbage collection.

Full code:
```python
import os, sys, gc
from ctypes import *

class S(Structure):
_fields_ = [ ("x", POINTER(c_int)), ("y", POINTER(c_int)) ]

def __del__(self):
print("__del__ was called")

def dump_mem(): os.system(f"ps -o rss {os.getpid()}")

dump_mem() # ~ 6 MB

s = S()
s.x = (c_int * 10**8)()
s.y = s.x

dump_mem() # ~ 397 MB

del s # prints "__del__ was called" immediatly

dump_mem() # ~ 397 MB

gc.collect()

dump_mem() # ~ 6 MB
```

--
components: ctypes
messages: 378262
nosy: maxim.pichler
priority: normal
severity: normal
status: open
title: ctypes array inside structure requires explicit garbage collection
type: behavior
versions: Python 3.8

___
Python tracker 

___
___
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com