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

Skip to content

Commit 29f43f7

Browse files
committed
Issue #12881: ctypes: Fix segfault with large structure field names.
2 parents 7f3140e + 1efb33a commit 29f43f7

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
@@ -1303,6 +1303,8 @@ Tools/Demos
13031303
Extension Modules
13041304
-----------------
13051305

1306+
- Issue #12881: ctypes: Fix segfault with large structure field names.
1307+
13061308
- Issue #13058: ossaudiodev: fix a file descriptor leak on error. Patch by
13071309
Thomas Jarosch.
13081310

Modules/_ctypes/stgdict.c

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

495495
len = strlen(fieldname) + strlen(fieldfmt);
496-
buf = alloca(len + 2 + 1);
497496

497+
buf = PyMem_Malloc(len + 2 + 1);
498+
if (buf == NULL) {
499+
Py_DECREF(pair);
500+
PyErr_NoMemory();
501+
return -1;
502+
}
498503
sprintf(buf, "%s:%s:", fieldfmt, fieldname);
499504

500505
ptr = stgdict->format;
501506
stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf);
502507
PyMem_Free(ptr);
508+
PyMem_Free(buf);
503509

504510
if (stgdict->format == NULL) {
505511
Py_DECREF(pair);

0 commit comments

Comments
 (0)