[issue14596] struct.unpack memory leak

Serhiy Storchaka report at bugs.python.org
Mon Apr 23 23:01:56 CEST 2012


Serhiy Storchaka <storchaka at gmail.com> added the comment:

Here is a patch that implements method __sizeof__ for Struct. This can
be used to limit the caching. In any case, it is useful to know the real
memory consumption of the object.

I'm not sure of the correctness of the method implementation.

----------
Added file: http://bugs.python.org/file25325/struct_sizeof.patch

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue14596>
_______________________________________
-------------- next part --------------
diff -r c820aa9c0c00 Modules/_struct.c
--- a/Modules/_struct.c	Fri Apr 20 18:04:03 2012 -0400
+++ b/Modules/_struct.c	Mon Apr 23 16:57:18 2012 +0300
@@ -1752,6 +1752,19 @@
     return PyLong_FromSsize_t(self->s_size);
 }
 
+static PyObject *
+s_sizeof(PyStructObject *self, void *unused)
+{
+    Py_ssize_t res;
+    formatcode *code;
+
+    res = sizeof(PyStructObject) + sizeof(formatcode);
+    for (code = self->s_codes; code->fmtdef != NULL; code++) {
+        res += sizeof(formatcode);
+    }
+    return PyLong_FromSsize_t(res);
+}
+
 /* List of functions */
 
 static struct PyMethodDef s_methods[] = {
@@ -1760,6 +1773,8 @@
     {"unpack",          s_unpack,       METH_O, s_unpack__doc__},
     {"unpack_from",     (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
                     s_unpack_from__doc__},
+    {"__sizeof__",      (PyCFunction)s_sizeof, METH_NOARGS,
+     "Returns size in memory, in bytes"},
     {NULL,       NULL}          /* sentinel */
 };
 


More information about the Python-bugs-list mailing list