Skip to content

gh-159514: Fix tuple item reference leak on resize allocation failure - #159526

Open
zolaski333 wants to merge 2 commits into
python:mainfrom
zolaski333:gh-159514-tuple-resize-leak
Open

zolaski333 wants to merge 2 commits into
python:mainfrom
zolaski333:gh-159514-tuple-resize-leak

Conversation

@zolaski333

@zolaski333 zolaski333 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

_PyTuple_Resize() frees the tuple storage after a failed PyObject_GC_Resize() without releasing its item references. Release the remaining items before freeing the storage. Py_XDECREF() also handles entries already cleared during shrinking.

Add a regression test that forces MemoryError through the allocator's checked size limit and verifies that the item is released. It fails before the fix and passes afterwards.

The leak was also reproduced by calling _PyTuple_Resize() directly through ctypes.pythonapi, without _testcapi: the caller's pointer became NULL, but the item remained alive. The _testcapi wrapper is unchanged.

Validation on Windows x64 Debug:

  • test_capi.test_tuple, test_capi.test_mem and test_tuple pass in the standard build and the free-threaded build with the GIL disabled and enabled.
  • test_capi.test_tuple passes -R 3:3 in both builds.
  • Allocation-failure checks cover growing, shrinking and NULL entries.
  • patchcheck and git diff --check pass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant