From 422467006e6be5374262dde6c74514774ec38326 Mon Sep 17 00:00:00 2001 From: Amrutha Date: Wed, 24 Jun 2026 02:01:47 +0530 Subject: [PATCH] gh-151842: Fix crash upon OOM in `_interpreters.capture_exception` (GH-151843) (cherry picked from commit 5e0747db2f5a063657a117e88b58a20624c848d1) Co-authored-by: Amrutha --- .../Library/2026-06-30-13-00-00.gh-issue-151842.OOM31g.rst | 2 ++ Modules/_interpretersmodule.c | 4 +++- Python/crossinterp.c | 2 ++ 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-06-30-13-00-00.gh-issue-151842.OOM31g.rst diff --git a/Misc/NEWS.d/next/Library/2026-06-30-13-00-00.gh-issue-151842.OOM31g.rst b/Misc/NEWS.d/next/Library/2026-06-30-13-00-00.gh-issue-151842.OOM31g.rst new file mode 100644 index 000000000000000..8a2ecf3c40032f5 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-06-30-13-00-00.gh-issue-151842.OOM31g.rst @@ -0,0 +1,2 @@ +Fix a crash in :func:`!_interpreters.capture_exception` when +:exc:`MemoryError` happens. Patch by Amrutha Modela. diff --git a/Modules/_interpretersmodule.c b/Modules/_interpretersmodule.c index faf3b25b68c4eb3..70adb59d6fdd54c 100644 --- a/Modules/_interpretersmodule.c +++ b/Modules/_interpretersmodule.c @@ -1580,7 +1580,9 @@ capture_exception(PyObject *self, PyObject *args, PyObject *kwds) } finally: - _PyXI_FreeExcInfo(info); + if (info != NULL) { + _PyXI_FreeExcInfo(info); + } if (exc != exc_arg) { if (PyErr_Occurred()) { PyErr_SetRaisedException(exc); diff --git a/Python/crossinterp.c b/Python/crossinterp.c index ba31f356d511f0e..143b77996481467 100644 --- a/Python/crossinterp.c +++ b/Python/crossinterp.c @@ -1648,6 +1648,7 @@ _PyXI_NewExcInfo(PyObject *exc) } _PyXI_excinfo *info = PyMem_RawCalloc(1, sizeof(_PyXI_excinfo)); if (info == NULL) { + PyErr_NoMemory(); return NULL; } const char *failure; @@ -1668,6 +1669,7 @@ _PyXI_NewExcInfo(PyObject *exc) void _PyXI_FreeExcInfo(_PyXI_excinfo *info) { + assert(info != NULL); _PyXI_excinfo_clear(info); PyMem_RawFree(info); }