#3322: bounds checking for _json.scanstring
diff --git a/Modules/_json.c b/Modules/_json.c
index ea6d66f..88510a7 100644
--- a/Modules/_json.c
+++ b/Modules/_json.c
@@ -235,6 +235,10 @@
     if (chunks == NULL) {
         goto bail;
     }
+    if (end < 0 || len <= end) {
+        PyErr_SetString(PyExc_ValueError, "end is out of bounds");
+        goto bail;
+    }
     while (1) {
         /* Find the end of the string or the next escape */
         Py_UNICODE c = 0;
@@ -245,7 +249,7 @@
                 break;
             }
             else if (strict && c <= 0x1f) {
-                raise_errmsg("Invalid control character at", pystr, begin);
+                raise_errmsg("Invalid control character at", pystr, next);
                 goto bail;
             }
         }
@@ -396,6 +400,10 @@
     if (chunks == NULL) {
         goto bail;
     }
+    if (end < 0 || len <= end) {
+        PyErr_SetString(PyExc_ValueError, "end is out of bounds");
+        goto bail;
+    }
     while (1) {
         /* Find the end of the string or the next escape */
         Py_UNICODE c = 0;
@@ -406,7 +414,7 @@
                 break;
             }
             else if (strict && c <= 0x1f) {
-                raise_errmsg("Invalid control character at", pystr, begin);
+                raise_errmsg("Invalid control character at", pystr, next);
                 goto bail;
             }
         }