From 8b4a48de46c0518a64a89bf72545947d701293cd Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Mon, 7 Sep 2026 17:51:34 +0200 Subject: [PATCH] gh-156943: Fix struct.pack('0p', bytes) If the Pascal string is empty (size=0), do not write the size prefix. Previously, a NUL byte was written outsize the buffer (buffer overflow). --- Modules/_struct.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Modules/_struct.c b/Modules/_struct.c index 352312fb0b4c19b..8caadf091767e3a 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -2424,7 +2424,9 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args, memcpy(res + 1, p, n); if (n > 255) n = 255; - *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char); + if (n > 0) { + *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char); + } } else { if (e->pack(state, res, v, e) < 0) { if (PyLong_Check(v) && PyErr_ExceptionMatches(PyExc_OverflowError))