bpo-35436: Add missing PyErr_NoMemory() calls and other minor bug fixes. (GH-11015) (GH-11020)

(cherry picked from commit 4c49da0cb7434c676d70b9ccf38aca82ac0d64a9)
diff --git a/Python/ast.c b/Python/ast.c
index 07227c2..1e182c7 100644
--- a/Python/ast.c
+++ b/Python/ast.c
@@ -4092,6 +4092,9 @@
     }
     /* Create a duplicate without underscores. */
     dup = PyMem_Malloc(strlen(s) + 1);
+    if (dup == NULL) {
+        return PyErr_NoMemory();
+    }
     end = dup;
     for (; *s; s++) {
         if (*s != '_') {
@@ -4326,8 +4329,10 @@
     len = expr_end - expr_start;
     /* Allocate 3 extra bytes: open paren, close paren, null byte. */
     str = PyMem_RawMalloc(len + 3);
-    if (str == NULL)
+    if (str == NULL) {
+        PyErr_NoMemory();
         return NULL;
+    }
 
     str[0] = '(';
     memcpy(str+1, expr_start, len);
diff --git a/Python/marshal.c b/Python/marshal.c
index 6d06266..7d60614 100644
--- a/Python/marshal.c
+++ b/Python/marshal.c
@@ -689,11 +689,12 @@
         p->buf_size = n;
     }
     else if (p->buf_size < n) {
-        p->buf = PyMem_REALLOC(p->buf, n);
-        if (p->buf == NULL) {
+        char *tmp = PyMem_REALLOC(p->buf, n);
+        if (tmp == NULL) {
             PyErr_NoMemory();
             return NULL;
         }
+        p->buf = tmp;
         p->buf_size = n;
     }
 
diff --git a/Python/pystrtod.c b/Python/pystrtod.c
index 461e8dc..fea7e45 100644
--- a/Python/pystrtod.c
+++ b/Python/pystrtod.c
@@ -398,6 +398,9 @@
     }
 
     dup = PyMem_Malloc(orig_len + 1);
+    if (dup == NULL) {
+        return PyErr_NoMemory();
+    }
     end = dup;
     prev = '\0';
     last = s + orig_len;