diff --git a/Misc/NEWS.d/next/Library/2026-10-20-00-00-00.gh-issue-159739.eb8987.rst b/Misc/NEWS.d/next/Library/2026-10-20-00-00-00.gh-issue-159739.eb8987.rst new file mode 100644 index 00000000000000..11c88411bb9125 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-10-20-00-00-00.gh-issue-159739.eb8987.rst @@ -0,0 +1,2 @@ +Avoid undefined behavior when :func:`struct.pack_into` copies a bytearray into +overlapping output. diff --git a/Modules/_struct.c b/Modules/_struct.c index 1e5d52b758f7e2..fad026ac8a4652 100644 --- a/Modules/_struct.c +++ b/Modules/_struct.c @@ -2409,7 +2409,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args, if (n > code->size) n = code->size; if (n > 0) - memcpy(res, p, n); + memmove(res, p, n); } else if (strcmp(e->format, "p") == 0) { Py_ssize_t n; int isstring; @@ -2435,7 +2435,7 @@ s_pack_internal(PyStructObject *soself, PyObject *const *args, n = code->size - 1; } if (n > 0) - memcpy(res + 1, p, n); + memmove(res + 1, p, n); if (n > 255) n = 255; if (n > 0) {