in scan_once, prevent the reading of arbitrary memory when passed a negative index

Bug reported by Guido Vranken.
diff --git a/Lib/json/tests/test_decode.py b/Lib/json/tests/test_decode.py
index ffd1aa4..78d7fbb 100644
--- a/Lib/json/tests/test_decode.py
+++ b/Lib/json/tests/test_decode.py
@@ -60,5 +60,10 @@
         msg = 'escape'
         self.assertRaisesRegexp(ValueError, msg, self.loads, s)
 
+    def test_negative_index(self):
+        d = self.json.JSONDecoder()
+        self.assertRaises(ValueError, d.raw_decode, 'a'*42, -50000)
+        self.assertRaises(ValueError, d.raw_decode, u'a'*42, -50000)
+
 class TestPyDecode(TestDecode, PyTest): pass
 class TestCDecode(TestDecode, CTest): pass
diff --git a/Misc/ACKS b/Misc/ACKS
index 2fd7e33..a618002 100644
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -1369,6 +1369,7 @@
 Frank Visser
 Johannes Vogel
 Alex Volkov
+Guido Vranken
 Martijn Vries
 Sjoerd de Vries
 Niki W. Waibel
diff --git a/Misc/NEWS b/Misc/NEWS
index 7fef5b5..79eaada 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -43,6 +43,9 @@
 Library
 -------
 
+- Fix arbitrary memory access in JSONDecoder.raw_decode with a negative second
+  parameter. Bug reported by Guido Vranken.
+
 - Issue #21172: isinstance check relaxed from dict to collections.Mapping.
 
 - Issue #21191: In os.fdopen, alwyas close the file descriptor when an exception
diff --git a/Modules/_json.c b/Modules/_json.c
index eb4368a..56d9ee4 100644
--- a/Modules/_json.c
+++ b/Modules/_json.c
@@ -1468,7 +1468,10 @@
     PyObject *res;
     char *str = PyString_AS_STRING(pystr);
     Py_ssize_t length = PyString_GET_SIZE(pystr);
-    if (idx >= length) {
+    if (idx < 0)
+        /* Compatibility with the Python version. */
+        idx += length;
+    if (idx < 0 || idx >= length) {
         PyErr_SetNone(PyExc_StopIteration);
         return NULL;
     }
@@ -1555,7 +1558,10 @@
     PyObject *res;
     Py_UNICODE *str = PyUnicode_AS_UNICODE(pystr);
     Py_ssize_t length = PyUnicode_GET_SIZE(pystr);
-    if (idx >= length) {
+    if (idx < 0)
+        /* Compatibility with Python version. */
+        idx += length;
+    if (idx < 0 || idx >= length) {
         PyErr_SetNone(PyExc_StopIteration);
         return NULL;
     }