Skip to content

Commit 401fdf9

Browse files
authored
gh-101037: Fix potential memory underallocation for zeros of int subtypes (#101038)
This PR fixes object allocation in long_subtype_new to ensure that there's at least one digit in all cases, and makes sure that the value of that digit is copied over from the source long. Needs backport to 3.11, but not any further: the change to require at least one digit was only introduced for Python 3.11. Fixes #101037.
1 parent 9e94767 commit 401fdf9

File tree

3 files changed

+10
-0
lines changed

3 files changed

+10
-0
lines changed

Include/cpython/longintrepr.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@ typedef long stwodigits; /* signed variant of twodigits */
7171
0 <= ob_digit[i] <= MASK.
7272
The allocation function takes care of allocating extra memory
7373
so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.
74+
We always allocate memory for at least one digit, so accessing ob_digit[0]
75+
is always safe. However, in the case ob_size == 0, the contents of
76+
ob_digit[0] may be undefined.
7477
7578
CAUTION: Generic code manipulating subtypes of PyVarObject has to
7679
aware that ints abuse ob_size's sign bit.
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix potential memory underallocation issue for instances of :class:`int`
2+
subclasses with value zero.

Objects/longobject.c

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5638,6 +5638,11 @@ long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
56385638
n = Py_SIZE(tmp);
56395639
if (n < 0)
56405640
n = -n;
5641+
/* Fast operations for single digit integers (including zero)
5642+
* assume that there is always at least one digit present. */
5643+
if (n == 0) {
5644+
n = 1;
5645+
}
56415646
newobj = (PyLongObject *)type->tp_alloc(type, n);
56425647
if (newobj == NULL) {
56435648
Py_DECREF(tmp);

0 commit comments

Comments
 (0)