https://github.com/python/cpython/commit/b2894626aac6c44bf11f64d596f4aa52e0d5caea
commit: b2894626aac6c44bf11f64d596f4aa52e0d5caea
branch: 3.13
author: Ramin Farajpour Cami <[email protected]>
committer: encukou <[email protected]>
date: 2026-03-09T17:41:45+01:00
summary:

[3.13] gh-145623: Fix crashes on uninitialized struct.Struct objects 
(gh-145624) (GH-145631)

files:
A Misc/NEWS.d/next/Library/2026-03-07-15-00-00.gh-issue-145623.2Y7LzT.rst
M Lib/test/test_struct.py
M Modules/_struct.c

diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py
index e602eeb6289808..a3f8fad7a9a0f9 100644
--- a/Lib/test/test_struct.py
+++ b/Lib/test/test_struct.py
@@ -806,6 +806,8 @@ def test_operations_on_half_initialized_Struct(self):
         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
index 00000000000000..77b43e79e35860
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-03-07-15-00-00.gh-issue-145623.2Y7LzT.rst
@@ -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__()``.
diff --git a/Modules/_struct.c b/Modules/_struct.c
index 55b32f074779b7..c3ca125e41ab64 100644
--- a/Modules/_struct.c
+++ b/Modules/_struct.c
@@ -2196,6 +2196,7 @@ PyDoc_STRVAR(s_sizeof__doc__,
 static PyObject *
 s_sizeof(PyStructObject *self, void *unused)
 {
+    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);
@@ -2206,6 +2207,7 @@ s_sizeof(PyStructObject *self, void *unused)
 static PyObject *
 s_repr(PyStructObject *self)
 {
+    ENSURE_STRUCT_IS_READY(self);
     PyObject* fmt = PyUnicode_FromStringAndSize(
         PyBytes_AS_STRING(self->s_format), PyBytes_GET_SIZE(self->s_format));
     if (fmt == NULL) {

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to