Skip to content

Commit

Permalink
pythongh-100637: Fix int and bool __sizeof__ calculation to include t…
Browse files Browse the repository at this point in the history
…he 1 element ob_digit array for 0 and False (pythonGH-100663)

Fixes behaviour where int (and subtypes like bool) __sizeof__ under-reports true size as it did not take into account the size 1 `ob_digit` array for the zero int.

(cherry picked from commit d7e7f79)

Co-authored-by: Ionite <dev@ionite.io>
Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
  • Loading branch information
2 people authored and miss-islington committed Jan 3, 2023
1 parent b99ac1d commit cae7453
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 2 deletions.
3 changes: 2 additions & 1 deletion Lib/test/test_sys.py
Original file line number Diff line number Diff line change
Expand Up @@ -1322,6 +1322,7 @@ def test_objecttypes(self):
check = self.check_sizeof
# bool
check(True, vsize('') + self.longdigit)
check(False, vsize('') + self.longdigit)
# buffer
# XXX
# builtin_function_or_method
Expand Down Expand Up @@ -1459,7 +1460,7 @@ def get_gen(): yield 1
# listreverseiterator (list)
check(reversed([]), size('nP'))
# int
check(0, vsize(''))
check(0, vsize('') + self.longdigit)
check(1, vsize('') + self.longdigit)
check(-1, vsize('') + self.longdigit)
PyLong_BASE = 2**sys.int_info.bits_per_digit
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :func:`int.__sizeof__` calculation to include the 1 element ob_digit array for 0 and False.
5 changes: 4 additions & 1 deletion Objects/longobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -5661,7 +5661,10 @@ int___sizeof___impl(PyObject *self)
{
Py_ssize_t res;

res = offsetof(PyLongObject, ob_digit) + Py_ABS(Py_SIZE(self))*sizeof(digit);
res = offsetof(PyLongObject, ob_digit)
/* using Py_MAX(..., 1) because we always allocate space for at least
one digit, even though the integer zero has a Py_SIZE of 0 */
+ Py_MAX(Py_ABS(Py_SIZE(self)), 1)*sizeof(digit);
return res;
}

Expand Down

0 comments on commit cae7453

Please sign in to comment.