Skip to content

Commit 45aa6a3

Browse files
committed
Fix: Prevent crash in ctypes.CField when byte_size does not match type size (gh-132470)
When creating a ctypes.CField with an incorrect byte_size (e.g., using byte_size=2 for ctypes.c_byte), the code would previously abort due to the failed assertion byte_size == info->size. This commit replaces the assertion with a proper error handling mechanism that raises a ValueError when byte_size does not match the expected type size. This prevents the crash and provides a more informative error message to the us
1 parent a214db0 commit 45aa6a3

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

Modules/_ctypes/cfield.c

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,12 @@ PyCField_new_impl(PyTypeObject *type, PyObject *name, PyObject *proto,
9999
"type of field %R must be a C type", name);
100100
goto error;
101101
}
102-
assert(byte_size == info->size);
102+
if (byte_size != info->size) {
103+
PyErr_Format(PyExc_ValueError,
104+
"byte size of field %R (%zd) does not match type size (%zd)",
105+
name, byte_size, info->size);
106+
goto error;
107+
}
103108

104109
Py_ssize_t bitfield_size = 0;
105110
Py_ssize_t bit_offset = 0;

0 commit comments

Comments
 (0)