diff -r 6374b4ffe00c Lib/ctypes/test/test_structures.py --- a/Lib/ctypes/test/test_structures.py Fri Sep 02 23:19:52 2011 +0200 +++ b/Lib/ctypes/test/test_structures.py Sat Sep 03 11:10:31 2011 -0500 @@ -326,6 +326,18 @@ else: self.assertEqual(msg, "(Phone) TypeError: too many initializers") + def test_huge_field_name(self): + # issue12881: segfault with large structure field names + def create_class(length): + class S(Structure): + _fields_ = [('x' * length, c_int)] + + for length in [10 ** i for i in range(0, 8)]: + try: + create_class(length) + except MemoryError: + # MemoryErrors are OK, we just don't want to segfault + pass def get_except(self, func, *args): try: diff -r 6374b4ffe00c Modules/_ctypes/stgdict.c --- a/Modules/_ctypes/stgdict.c Fri Sep 02 23:19:52 2011 +0200 +++ b/Modules/_ctypes/stgdict.c Sat Sep 03 11:10:31 2011 -0500 @@ -493,14 +493,19 @@ } len = strlen(fieldname) + strlen(fieldfmt); - buf = alloca(len + 2 + 1); - + buf = PyMem_Malloc(len + 2 + 1); + if (buf == NULL) { + Py_DECREF(pair); + PyErr_NoMemory(); + return -1; + } sprintf(buf, "%s:%s:", fieldfmt, fieldname); ptr = stgdict->format; stgdict->format = _ctypes_alloc_format_string(stgdict->format, buf); PyMem_Free(ptr); - + PyMem_Free(buf); + if (stgdict->format == NULL) { Py_DECREF(pair); return -1;