https://github.com/python/cpython/commit/1c5df824718f2ad7124102b6db6f7039793676d0
commit: 1c5df824718f2ad7124102b6db6f7039793676d0
branch: 3.13
author: Miss Islington (bot) <[email protected]>
committer: vstinner <[email protected]>
date: 2026-09-07T19:57:45Z
summary:

[3.13] gh-156939: Fix struct.pack('0p', bytes) (GH-157071) (#157131)

gh-156939: Fix struct.pack('0p', bytes) (GH-157071)

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). In practice, the write remains into allocated memory
and is silently ignored: no memory is corrupted.
(cherry picked from commit 23525c90f539f621c802f2725e91ff234a69e1e0)

Co-authored-by: Victor Stinner <[email protected]>

files:
M Modules/_struct.c

diff --git a/Modules/_struct.c b/Modules/_struct.c
index 36d5ece390e8a2..c5a6c5c0787b0f 100644
--- a/Modules/_struct.c
+++ b/Modules/_struct.c
@@ -2020,7 +2020,9 @@ s_pack_internal(PyStructObject *soself, PyObject *const 
*args, int offset,
                     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))

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to