Skip to content

Refcount leak in finalize_remove_modules() #144307

Closed

Description

@hyongtao-code

Bug report

Bug description:

There is a reference leak in finalize_remove_modules() (pylifecycle.c).

In the iterator-based cleanup path, PyIter_Next() returns a new reference
for key, but if PyObject_GetItem(modules, key) fails, the code continues
without DECREF'ing key.

The fix is to add Py_DECREF(key) before continue;.

Minimal fix:

PyObject *key;
while ((key = PyIter_Next(iterator))) {
    PyObject *value = PyObject_GetItem(modules, key);
    if (value == NULL) {
        PyErr_FormatUnraisable("Exception ignored while removing modules");
        Py_DECREF(key);      <--------------------here
        continue;
    }
    CLEAR_MODULE(key, value);
    Py_DECREF(value);
    Py_DECREF(key);
}
if (PyErr_Occurred()) {
    PyErr_FormatUnraisable("Exception ignored while removing modules");
}
Py_DECREF(iterator);

CPython versions tested on:

CPython main branch

Operating systems tested on:

Windows

Linked PRs

Activity

  1. added
    type-bug
    on Jan 28, 2026
  2. added
    interpreter-core
    on Jan 28, 2026
  3. added a commit that references this issue on Jan 29, 2026
  4. added a commit that references this issue on Jan 29, 2026
  5. ZeroIntensity commented on Jan 29, 2026

    @ZeroIntensity
    Member

    Backports are on auto-merge, thanks for the fix!

  6. added 3 commits that reference this issue on Jan 29, 2026
  7. added a commit that references this issue on Feb 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-coretype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions