Skip to content

Refcount leak in finalize_remove_modules() #144307

@hyongtao-code

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions