The module-global curses_screen_encoding in Modules/_cursesmodule.c stores a borrowed pointer to the encoding string owned by the window object that initscr() returns:
It is set only on the first initscr() call and is never updated afterwards. That first window object can be deallocated while the pointer is still needed: the module-level functions unctrl() and ungetch() have no window of their own and fall back to curses_screen_encoding to encode non-ASCII characters. Once the originating window is gone, those functions read freed memory.
It can be reached from Python by dropping the initial screen and then encoding a non-ASCII character, e.g.:
The fix is to keep a private copy of the encoding instead of borrowing the window's, refreshed on every initscr() and released when the module is torn down.
Activity
gh-151695: Fix use-after-free of the curses screen encoding (GH-151696)
[3.15] gh-151695: Fix use-after-free of the curses screen encoding (G…
[3.14] pythongh-151695: Fix use-after-free of the curses screen encod…
[3.14] gh-151695: Fix use-after-free of the curses screen encoding (G…
[3.13] gh-151695: Fix use-after-free of the curses screen encoding (G…
pythongh-151695: Fix use-after-free of the curses screen encoding (py…