[3.13] gh-151126: Fix `PyErr_NoMemory` errors in `_ctypes.c` (GH-152720) (#153708)

Yhg1s <[email protected]> Tue, 04 Aug 2026 04:57:47 -0400 (EDT)
Newsgroups gmane.comp.python.cvs
Message-ID <[email protected]>
https://github.com/python/cpython/commit/3c431d5a9867c429f0029a4b57fe398a5d3bcd89
commit: 3c431d5a9867c429f0029a4b57fe398a5d3bcd89
branch: 3.13
author: Miss Islington (bot) <[email protected]>
committer: Yhg1s <[email protected]>
date: 2026-08-04T10:57:32+02:00
summary:

[3.13] gh-151126: Fix `PyErr_NoMemory`  errors in `_ctypes.c`  (GH-152720) (#153708)

gh-151126: Fix `PyErr_NoMemory`  errors in `_ctypes.c`  (GH-152720)
(cherry picked from commit d807210fee5606f8d504c1677f7e5ecb5f208a1e)

Co-authored-by: stevens <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-07-01-11-29-13.gh-issue-151126.eElGy5.rst
M Modules/_ctypes/_ctypes.c

diff --git a/Misc/NEWS.d/next/Library/2026-07-01-11-29-13.gh-issue-151126.eElGy5.rst b/Misc/NEWS.d/next/Library/2026-07-01-11-29-13.gh-issue-151126.eElGy5.rst
new file mode 100644
index 000000000000000..d5ec1d254ef056e
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-07-01-11-29-13.gh-issue-151126.eElGy5.rst
@@ -0,0 +1,3 @@
+Fix a crash caused by failing to set :exc:`MemoryError` on allocation failure
+when passing :class:`ctypes.Structure` or :class:`ctypes.Union` instances by
+value to ctypes foreign functions.
diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c
index c66d157be75e3ae..fb22d938a003a7c 100644
--- a/Modules/_ctypes/_ctypes.c
+++ b/Modules/_ctypes/_ctypes.c
@@ -594,6 +594,7 @@ StructUnionType_paramfunc(ctypes_state *st, CDataObject *self)
     if ((size_t)self->b_size > sizeof(void*)) {
         ptr = PyMem_Malloc(self->b_size);
         if (ptr == NULL) {
+            PyErr_NoMemory();
             return NULL;
         }
         memcpy(ptr, self->b_ptr, self->b_size);

_______________________________________________
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]