Skip to content

Commit b7e483b

Browse files
bpo-36791: Safer detection of integer overflow in sum(). (GH-13080)
(cherry picked from commit 2950073) Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
1 parent 4f5febd commit b7e483b

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
@@ -2374,9 +2374,11 @@ builtin_sum_impl(PyObject *module, PyObject *iterable, PyObject *start)
23742374
}
23752375
if (PyLong_CheckExact(item)) {
23762376
long b = PyLong_AsLongAndOverflow(item, &overflow);
2377-
long x = i_result + b;
2378-
if (overflow == 0 && ((x^i_result) >= 0 || (x^b) >= 0)) {
2379-
i_result = x;
2377+
if (overflow == 0 &&
2378+
(i_result >= 0 ? (b <= LONG_MAX - i_result)
2379+
: (b >= LONG_MIN - i_result)))
2380+
{
2381+
i_result += b;
23802382
Py_DECREF(item);
23812383
continue;
23822384
}

0 commit comments

Comments
 (0)