0

e.g.

import gc
import ctypes as ct

a=1
address=id(a)
# this moment to del the var
del a 
# and callback 
gc.collect()
# now use address to get content
content=ct.cast(address,ct.py_object).value
# and print, the program show 1 
print(content)

The result is like this:

Python 3.8.0 |Anaconda, Inc.| (default, Dec 29 2018, 19:04:46)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license()" for more information.
>>> a = 1
>>> a
1
>>> id(a)
4334421424
>>> import gc
>>> import ctypes
>>> del a
>>> a
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a
NameError: name 'a' is not defined
>>> gc.collect()
22
>>> ctypes.cast(4334421424, ctypes.py_object).value
1
>>> 

Question: After the gc.collect(), why the address can still find the content?

Red
  • 26,798
  • 7
  • 36
  • 58
peanut
  • 11
  • 1
    Accessing arbitrary memory locations is undefined behavior. – user2357112 May 26 '20 at 03:30
  • Note, `gc.collect()` does **nothing useful here**, it is entirely irrelevant. – juanpa.arrivillaga May 26 '20 at 03:33
  • @user2357112supportsMonica perhaps it might be useful to add an answer that is geared towards Python. – juanpa.arrivillaga May 26 '20 at 03:36
  • 1
    (It happens to be the case that this object wasn't collected, due to a lingering reference in the code object's `co_consts`, and a lot of references due to small integer caching implementation details, but even without those references, Python doesn't promise to crash or clear a collected object's memory or do anything different from what happened in this test.) – user2357112 May 26 '20 at 03:39

0 Answers0