diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-16-00-00.gh-issue-151773.mN4kRt.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-16-00-00.gh-issue-151773.mN4kRt.rst new file mode 100644 index 000000000000000..b4193c5e15ffef8 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-06-21-16-00-00.gh-issue-151773.mN4kRt.rst @@ -0,0 +1,2 @@ +Fix a crash in :func:`contextvars.ContextVar.set` when memory allocation +fails. diff --git a/Python/context.c b/Python/context.c index 593e6ef90037cfa..4678054ff3ad743 100644 --- a/Python/context.c +++ b/Python/context.c @@ -362,6 +362,9 @@ PyContextVar_Set(PyObject *ovar, PyObject *val) Py_XINCREF(old_val); PyContextToken *tok = token_new(ctx, var, old_val); Py_XDECREF(old_val); + if (tok == NULL) { + return NULL; + } if (contextvar_set(var, val)) { Py_DECREF(tok);