8000 [3.11] gh-101037: Fix potential memory underallocation for zeros of i… · python/cpython@d2aaf81 · GitHub
[go: up one dir, main page]

Skip to content

Commit d2aaf81

Browse files
[3.11] gh-101037: Fix potential memory underallocation for zeros of int subtypes (GH-101038) (#101219)
gh-101037: Fix potential memory underallocation for zeros of int subtypes (GH-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 GH-101037. (cherry picked from commit 401fdf9) Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
1 parent 99da75e commit d2aaf81

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
@@ -5415,6 +5415,11 @@ long_subtype_new(PyTypeObject *type, PyObject *x, PyObject *obase)
54155415
n = Py_SIZE(tmp);
54165416
if (n < 0)
54175417
n = -n;
5418+
/* Fast operations for single digit integers (including zero)
5419+
* assume that there is always at least one digit present. */
5420+
if (n == 0) {
5421+
n = 1;
5422+
}
54185423
newobj = (PyLongObject *)type->tp_alloc(type, n);
54195424
if (newobj == NULL) {
54205425
Py_DECREF(tmp);

0 commit comments

Comments
 (0)
0