Issue 27812: PyFrameObject.f_gen can be left pointing to a dangling generator (original) (raw)

PyFrameObject.f_gen is a pointer (not a reference) to a generator/coroutine object. But the latter doesn't always correctly clean it up when it dies. This pointer is used by frame.clear().

Here is an example I made, which ends in a segfault. This example assumes we apply the patch of first, otherwise it just crashes earlier in the same way as .

# execute this with "python -Werror"
import gc
async def f():
    pass
cr = f()
frame = cr.cr_frame
del cr
gc.collect()
# create some randomness to reuse the memory just freed by 'cr'
import asyncio
print("ping")
frame.clear()

Patch attached. No test, but you can copy the above example.