[Python-checkins] cpython (2.7): detect overflow in combinations (closes #23366)

benjamin.peterson python-checkins at python.org
Mon Feb 2 03:05:12 CET 2015


https://hg.python.org/cpython/rev/fe203370c049
changeset:   94451:fe203370c049
branch:      2.7
parent:      94446:1cc37c52fed4
user:        Benjamin Peterson <benjamin at python.org>
date:        Sun Feb 01 20:59:00 2015 -0500
summary:
  detect overflow in combinations (closes #23366)

files:
  Lib/test/test_itertools.py |  5 +++++
  Misc/NEWS                  |  2 ++
  Modules/itertoolsmodule.c  |  4 ++++
  3 files changed, 11 insertions(+), 0 deletions(-)


diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -137,6 +137,11 @@
                 self.assertEqual(result, list(combinations2(values, r))) # matches second pure python version
                 self.assertEqual(result, list(combinations3(values, r))) # matches second pure python version
 
+    @test_support.bigaddrspacetest
+    def test_combinations_overflow(self):
+        with self.assertRaises(OverflowError):
+            combinations("AA", 2**29)
+
     @test_support.impl_detail("tuple reuse is specific to CPython")
     def test_combinations_tuple_reuse(self):
         self.assertEqual(len(set(map(id, combinations('abcde', 3)))), 1)
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -18,6 +18,8 @@
 Library
 -------
 
+- Issue #23366: Fixed possible integer overflow in itertools.combinations.
+
 - Issue #23191: fnmatch functions that use caching are now threadsafe.
 
 - Issue #18518: timeit now rejects statements which can't be compiled outside
diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c
--- a/Modules/itertoolsmodule.c
+++ b/Modules/itertoolsmodule.c
@@ -2093,6 +2093,10 @@
         goto error;
     }
 
+    if (r > PY_SSIZE_T_MAX/sizeof(Py_ssize_t)) {
+        PyErr_SetString(PyExc_OverflowError, "r is too big");
+        goto error;
+    }
     indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
     if (indices == NULL) {
         PyErr_NoMemory();

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list