bpo-38588: Fix possible crashes in dict and list when calling PyObject_RichCompareBool (GH-17734)

Take strong references before calling PyObject_RichCompareBool to protect against the case
where the object dies during the call.
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index 4afa19c..87f88ab 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -2777,9 +2777,11 @@
                     return -1;
                 return 0;
             }
+            Py_INCREF(bval);
             cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
             Py_DECREF(key);
             Py_DECREF(aval);
+            Py_DECREF(bval);
             if (cmp <= 0)  /* error or not equal */
                 return cmp;
         }
diff --git a/Objects/listobject.c b/Objects/listobject.c
index 86690f7..abe2604 100644
--- a/Objects/listobject.c
+++ b/Objects/listobject.c
@@ -2662,8 +2662,15 @@
 
     /* Search for the first index where items are different */
     for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
+        PyObject *vitem = vl->ob_item[i];
+        PyObject *witem = wl->ob_item[i];
+
+        Py_INCREF(vitem);
+        Py_INCREF(witem);
         int k = PyObject_RichCompareBool(vl->ob_item[i],
                                          wl->ob_item[i], Py_EQ);
+        Py_DECREF(vitem);
+        Py_DECREF(witem);
         if (k < 0)
             return NULL;
         if (!k)