Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1efb33a

Browse files
committed
Issue #12881: ctypes: Fix segfault with large structure field names.
1 parent 5d0de3f commit 1efb33a

3 files changed

Lines changed: 21 additions & 1 deletion

File tree

Lib/ctypes/test/test_structures.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,18 @@ class Person(Structure):
326326
else:
327327
self.assertEqual(msg, "(Phone) TypeError: too many initializers")
328328

329+
def test_huge_field_name(self):
330+
# issue12881: segfault with large structure field names
331+
def create_class(length):
332+
class S(Structure):
333+
_fields_ = [('x' * length, c_int)]
334+
335+
for length in [10 ** i for i in range(0, 8)]:
336+
try:
337+
create_class(length)
338+
except MemoryError:
339+
# MemoryErrors are OK, we just don't want to segfault
340+
pass
329341

330342
def get_except(self, func, *args):
331343
try:

Misc/NEWS

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,8 @@ Tests
8787
Extension Modules
8888
-----------------
8989

90+
- Issue #12881: ctypes: Fix segfault with large structure field names.
91+
9092
- Issue #13058: ossaudiodev: fix a file descriptor leak on error. Patch by
9193
Thomas Jarosch.
9294

Modules/_ctypes/stgdict.c

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -496,13 +496,19 @@ PyCStructUnionType_update_stgdict(PyObject *type, PyObject *fields, int isStruct
496496
}
497497

498498
len = strlen(fieldname) + strlen(fieldfmt);
499-
buf = alloca(len + 2 + 1);
500499

500+
buf = PyMem_Malloc(len + 2 + 1);
501+
if (buf == NULL) {
502+
Py_DECREF(pair);
503+
PyErr_NoMemory();
504+
return -1;
505+
}
501506
sprintf(buf, "%s:%s:", fieldfmt, fieldname);
502507

503508
ptr = stgdict->format;
504509
stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
505510
PyMem_Free(ptr);
511+
PyMem_Free(buf);
506512

507513
if (stgdict->format == NULL) {
508514
Py_DECREF(pair);

0 commit comments

Comments
 (0)