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);