Skip to content

Commit c992608

Browse files
committed
Issue 21375: Fix possible Py_ssizet overflow in heapq.
1 parent ceced6b commit c992608

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

Modules/_heapqmodule.c

+8-8
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ _siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
6262
static int
6363
_siftup(PyListObject *heap, Py_ssize_t pos)
6464
{
65-
Py_ssize_t startpos, endpos, childpos, rightpos;
65+
Py_ssize_t startpos, endpos, childpos, rightpos, limit;
6666
int cmp;
6767
PyObject *newitem, *tmp, *olditem;
6868
Py_ssize_t size;
@@ -79,9 +79,10 @@ _siftup(PyListObject *heap, Py_ssize_t pos)
7979
Py_INCREF(newitem);
8080

8181
/* Bubble up the smaller child until hitting a leaf. */
82-
childpos = 2*pos + 1; /* leftmost child position */
83-
while (childpos < endpos) {
82+
limit = endpos / 2; /* smallest pos that has no child */
83+
while (pos < limit) {
8484
/* Set childpos to index of smaller child. */
85+
childpos = 2*pos + 1; /* leftmost child position */
8586
rightpos = childpos + 1;
8687
if (rightpos < endpos) {
8788
cmp = PyObject_RichCompareBool(
@@ -108,7 +109,6 @@ _siftup(PyListObject *heap, Py_ssize_t pos)
108109
PyList_SET_ITEM(heap, pos, tmp);
109110
Py_DECREF(olditem);
110111
pos = childpos;
111-
childpos = 2*pos + 1;
112112
if (size != PyList_GET_SIZE(heap)) {
113113
PyErr_SetString(PyExc_RuntimeError,
114114
"list changed size during iteration");
@@ -419,7 +419,7 @@ _siftdownmax(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
419419
static int
420420
_siftupmax(PyListObject *heap, Py_ssize_t pos)
421421
{
422-
Py_ssize_t startpos, endpos, childpos, rightpos;
422+
Py_ssize_t startpos, endpos, childpos, rightpos, limit;
423423
int cmp;
424424
PyObject *newitem, *tmp;
425425

@@ -434,9 +434,10 @@ _siftupmax(PyListObject *heap, Py_ssize_t pos)
434434
Py_INCREF(newitem);
435435

436436
/* Bubble up the smaller child until hitting a leaf. */
437-
childpos = 2*pos + 1; /* leftmost child position */
438-
while (childpos < endpos) {
437+
limit = endpos / 2; /* smallest pos that has no child */
438+
while (pos < limit) {
439439
/* Set childpos to index of smaller child. */
440+
childpos = 2*pos + 1; /* leftmost child position */
440441
rightpos = childpos + 1;
441442
if (rightpos < endpos) {
442443
cmp = PyObject_RichCompareBool(
@@ -456,7 +457,6 @@ _siftupmax(PyListObject *heap, Py_ssize_t pos)
456457
Py_DECREF(PyList_GET_ITEM(heap, pos));
457458
PyList_SET_ITEM(heap, pos, tmp);
458459
pos = childpos;
459-
childpos = 2*pos + 1;
460460
}
461461

462462
/* The leaf at pos is empty now. Put newitem there, and bubble

0 commit comments

Comments
 (0)