From 6f6435b5a09baec29220ec6c1651cd243a77ee87 Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Wed, 21 Oct 2026 12:53:58 -0700 Subject: [PATCH] gh-159739: Keep SimpleQueue valid after buffer allocation fails If allocating a SimpleQueue buffer fails, the partially constructed object reports nonzero capacity despite having no storage. A subclass finalizer that calls put() then writes through a NULL pointer and crashes; publish the capacity only after allocation succeeds. Backport to 3.15 and 3.14. --- .../Library/2026-10-21-19-55-00.gh-issue-159739.sque01.rst | 2 ++ Modules/_queuemodule.c | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2026-10-21-19-55-00.gh-issue-159739.sque01.rst diff --git a/Misc/NEWS.d/next/Library/2026-10-21-19-55-00.gh-issue-159739.sque01.rst b/Misc/NEWS.d/next/Library/2026-10-21-19-55-00.gh-issue-159739.sque01.rst new file mode 100644 index 00000000000000..120caf1e27c6cb --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-21-19-55-00.gh-issue-159739.sque01.rst @@ -0,0 +1,2 @@ +Avoid a crash when a :class:`queue.SimpleQueue` subclass finalizer adds an +item after construction fails. diff --git a/Modules/_queuemodule.c b/Modules/_queuemodule.c index af54e42a6af584..6779193e402fac 100644 --- a/Modules/_queuemodule.c +++ b/Modules/_queuemodule.c @@ -51,13 +51,14 @@ RingBuf_Init(RingBuf *buf) { buf->put_idx = 0; buf->get_idx = 0; - buf->items_cap = INITIAL_RING_BUF_CAPACITY; + buf->items_cap = 0; buf->num_items = 0; - buf->items = PyMem_Calloc(buf->items_cap, sizeof(PyObject *)); + buf->items = PyMem_Calloc(INITIAL_RING_BUF_CAPACITY, sizeof(PyObject *)); if (buf->items == NULL) { PyErr_NoMemory(); return -1; } + buf->items_cap = INITIAL_RING_BUF_CAPACITY; return 0; }