bpo-29953: Fix memory leaks in the replace() method of datetime and t… (#933)

objects when pass out of bound fold argument.
(cherry picked from commit 314d6fca36a4eaa0541218431d14804fadec6488)
diff --git a/Modules/_datetimemodule.c b/Modules/_datetimemodule.c
index c784d0f..c2ad9a2 100644
--- a/Modules/_datetimemodule.c
+++ b/Modules/_datetimemodule.c
@@ -3926,16 +3926,16 @@
                                       time_kws,
                                       &hh, &mm, &ss, &us, &tzinfo, &fold))
         return NULL;
+    if (fold != 0 && fold != 1) {
+        PyErr_SetString(PyExc_ValueError,
+                        "fold must be either 0 or 1");
+        return NULL;
+    }
     tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
     if (tuple == NULL)
         return NULL;
     clone = time_new(Py_TYPE(self), tuple, NULL);
     if (clone != NULL) {
-        if (fold != 0 && fold != 1) {
-            PyErr_SetString(PyExc_ValueError,
-                            "fold must be either 0 or 1");
-            return NULL;
-        }
         TIME_SET_FOLD(clone, fold);
     }
     Py_DECREF(tuple);
@@ -5019,17 +5019,16 @@
                                       &y, &m, &d, &hh, &mm, &ss, &us,
                                       &tzinfo, &fold))
         return NULL;
+    if (fold != 0 && fold != 1) {
+        PyErr_SetString(PyExc_ValueError,
+                        "fold must be either 0 or 1");
+        return NULL;
+    }
     tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
     if (tuple == NULL)
         return NULL;
     clone = datetime_new(Py_TYPE(self), tuple, NULL);
-
     if (clone != NULL) {
-        if (fold != 0 && fold != 1) {
-            PyErr_SetString(PyExc_ValueError,
-                            "fold must be either 0 or 1");
-            return NULL;
-        }
         DATE_SET_FOLD(clone, fold);
     }
     Py_DECREF(tuple);