Skip to content

Commit 2950073

Browse files
bpo-36791: Safer detection of integer overflow in sum(). (GH-13080)
1 parent 88f07a8 commit 2950073

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

Python/bltinmodule.c

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2375,9 +2375,11 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
23752375
}
23762376
if (PyLong_CheckExact(item)) {
23772377
long b = PyLong_AsLongAndOverflow(item, &overflow);
2378-
long x = i_result + b;
2379-
if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2380-
i_result = x;
2378+
if (overflow == 0 &&
2379+
(i_result >= 0 ? (b <= LONG_MAX - i_result)
2380+
: (b >= LONG_MIN - i_result)))
2381+
{
2382+
i_result += b;
23812383
Py_DECREF(item);
23822384
continue;
23832385
}

0 commit comments

Comments
 (0)