From 5c3c4899a475f8b7d992e2abb9cd50e5a38f649e Mon Sep 17 00:00:00 2001 From: Sergey B Kirpichev Date: Wed, 15 Apr 2026 02:04:16 +0300 Subject: [PATCH 1/2] gh-148573: correct allocation of complex types in the ctypes Old code relying on implementation detail, that elements[1] for the FFI_TYPE_COMPLEX was never read. But this type actually shares same assumption as the FFI_TYPE_STRUCT: the elements field is a NULL-terminated array of pointers to ffi_type objects. So far for primitive types - only complex types have this struct field as non-NULL (two element array). --- Modules/_ctypes/_ctypes.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index 55eade1c8307ea..9899d75d31e400 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -2367,7 +2367,8 @@ PyCSimpleType_init(PyObject *self, PyObject *args, PyObject *kwds) stginfo->ffi_type_pointer = *fmt->pffi_type; } else { - const size_t els_size = sizeof(fmt->pffi_type->elements); + assert(fmt->pffi_type->type == FFI_TYPE_COMPLEX); + const size_t els_size = sizeof(2 * sizeof(ffi_type *)); stginfo->ffi_type_pointer.size = fmt->pffi_type->size; stginfo->ffi_type_pointer.alignment = fmt->pffi_type->alignment; stginfo->ffi_type_pointer.type = fmt->pffi_type->type; From dbea9c2cb63aabe5c08b0296fa5fa8809480a6d5 Mon Sep 17 00:00:00 2001 From: Sergey B Kirpichev Date: Wed, 15 Apr 2026 09:47:44 +0300 Subject: [PATCH 2/2] Update Modules/_ctypes/_ctypes.c Co-authored-by: sunmy2019 <59365878+sunmy2019@users.noreply.github.com> --- Modules/_ctypes/_ctypes.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c index 9899d75d31e400..a31e56264f325b 100644 --- a/Modules/_ctypes/_ctypes.c +++ b/Modules/_ctypes/_ctypes.c @@ -2368,7 +2368,7 @@ PyCSimpleType_init(PyObject *self, PyObject *args, PyObject *kwds) } else { assert(fmt->pffi_type->type == FFI_TYPE_COMPLEX); - const size_t els_size = sizeof(2 * sizeof(ffi_type *)); + const size_t els_size = 2 * sizeof(ffi_type *); stginfo->ffi_type_pointer.size = fmt->pffi_type->size; stginfo->ffi_type_pointer.alignment = fmt->pffi_type->alignment; stginfo->ffi_type_pointer.type = fmt->pffi_type->type;