pygame-ce icon indicating copy to clipboard operation
pygame-ce copied to clipboard

Fix window ub/segfault when quit/destroyed

Open ankith26 opened this issue 1 month ago • 1 comments
trafficstars

PR to fix #3601

The central issue here is that when pygame.quit/pygame.display.quit is called, all pygame window objects may hold invalid references in their attributes (like _win and surface). It therefore becomes necessary to do the equivalent of calling window.destroy on all active windows before doing the quit.

For this implementation, I went with a weakref approach where each window holds a self weakref upon creation. A new reference to this weakref is kept in a global set of weakrefs. Cleanup can happen in two paths:

  1. window is dealloc'ed before quit happens: in this case, that specific weakref is removed from our global set and cleaned up.
  2. quit happens before window(s) are dealloced: in this case we have to iterate over all weakrefs, deref them and call destroy on all windows.

This PR also adds a "window is alive" explicit check to all window methods/properties for consistent error raising.

tests will be added soon:tm:

ankith26 avatar Oct 09 '25 06:10 ankith26