]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-145623: Fix crashes on uninitialized struct.Struct objects (gh-145624)
authorRamin Farajpour Cami <ramin.blackhat@gmail.com>
Sat, 7 Mar 2026 13:31:45 +0000 (17:01 +0330)
committerGitHub <noreply@github.com>
Sat, 7 Mar 2026 13:31:45 +0000 (22:31 +0900)
Lib/test/test_struct.py
Misc/NEWS.d/next/Library/2026-03-07-15-00-00.gh-issue-145623.2Y7LzT.rst [new file with mode: 0644]
Modules/_struct.c

index aa793a2c223de9654ba5a12d82b546d4ee43cca0..4cbfd7ad8b1e484ad8e11d522d6033e9c0f057f8 100644 (file)
@@ -836,6 +836,8 @@ class StructTest(ComplexesAreIdenticalMixin, unittest.TestCase):
         self.assertRaises(RuntimeError, S.unpack, spam)
         self.assertRaises(RuntimeError, S.unpack_from, spam)
         self.assertRaises(RuntimeError, getattr, S, 'format')
+        self.assertRaises(RuntimeError, S.__sizeof__)
+        self.assertRaises(RuntimeError, repr, S)
         self.assertEqual(S.size, -1)
 
 
diff --git a/Misc/NEWS.d/next/Library/2026-03-07-15-00-00.gh-issue-145623.2Y7LzT.rst b/Misc/NEWS.d/next/Library/2026-03-07-15-00-00.gh-issue-145623.2Y7LzT.rst
new file mode 100644 (file)
index 0000000..77b43e7
--- /dev/null
@@ -0,0 +1,3 @@
+Fix crash in :mod:`struct` when calling :func:`repr` or
+``__sizeof__()`` on an uninitialized :class:`struct.Struct`
+object created via ``Struct.__new__()`` without calling ``__init__()``.
index ae8a8ffb3c005a58d72635f5660a86d096312e72..dcc3c7ec63e9e084cc701470c26a64876fc34be2 100644 (file)
@@ -2382,6 +2382,7 @@ static PyObject *
 Struct___sizeof___impl(PyStructObject *self)
 /*[clinic end generated code: output=2d0d78900b4cdb4e input=faca5925c1f1ffd0]*/
 {
+    ENSURE_STRUCT_IS_READY(self);
     size_t size = _PyObject_SIZE(Py_TYPE(self)) + sizeof(formatcode);
     for (formatcode *code = self->s_codes; code->fmtdef != NULL; code++) {
         size += sizeof(formatcode);
@@ -2393,6 +2394,7 @@ static PyObject *
 s_repr(PyObject *op)
 {
     PyStructObject *self = PyStructObject_CAST(op);
+    ENSURE_STRUCT_IS_READY(self);
     PyObject* fmt = PyUnicode_FromStringAndSize(
         PyBytes_AS_STRING(self->s_format), PyBytes_GET_SIZE(self->s_format));
     if (fmt == NULL) {