diff --git a/Misc/NEWS.d/next/Library/2026-07-21-16-13-43.gh-issue-154385.yQ6D2V.rst b/Misc/NEWS.d/next/Library/2026-07-21-16-13-43.gh-issue-154385.yQ6D2V.rst new file mode 100644 index 000000000000000..1c86b0d38bc6f68 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-07-21-16-13-43.gh-issue-154385.yQ6D2V.rst @@ -0,0 +1,2 @@ +Fix a potential crash in :func:`readline.get_begidx` and +:func:`readline.get_endidx` caused by an out-of-memory error. diff --git a/Modules/readline.c b/Modules/readline.c index 4c965e081c9d1a7..e160bd269c67039 100644 --- a/Modules/readline.c +++ b/Modules/readline.c @@ -1325,10 +1325,19 @@ flex_complete(const char *text, int start, int end) done: if (state) { - Py_XDECREF(state->begidx); - Py_XDECREF(state->endidx); - state->begidx = PyLong_FromLong((long) start); - state->endidx = PyLong_FromLong((long) end); + PyObject *begidx = PyLong_FromLong((long) start); + PyObject *endidx = PyLong_FromLong((long) end); + if (begidx == NULL || endidx == NULL) { + /* Keep the previous values so that get_begidx() and + get_endidx() never return NULL. */ + PyErr_Clear(); + Py_XDECREF(begidx); + Py_XDECREF(endidx); + } + else { + Py_XSETREF(state->begidx, begidx); + Py_XSETREF(state->endidx, endidx); + } } result = completion_matches((char *)text, *on_completion); PyGILState_Release(gilstate);