]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[2.7] bpo-18368: Fix memory leaks in PyOS_StdioReadline() when realloc() fails (GH...
authorstratakis <cstratak@redhat.com>
Tue, 19 Mar 2019 10:43:20 +0000 (11:43 +0100)
committerVictor Stinner <vstinner@redhat.com>
Tue, 19 Mar 2019 10:43:20 +0000 (11:43 +0100)
(cherry picked from commit 9ae513caa74a05970458dee17fb995ea49965bb5)

Misc/NEWS.d/next/Core and Builtins/2019-03-14-17-30-46.bpo-18368.WXaHAo.rst [new file with mode: 0644]
Parser/myreadline.c

diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-03-14-17-30-46.bpo-18368.WXaHAo.rst b/Misc/NEWS.d/next/Core and Builtins/2019-03-14-17-30-46.bpo-18368.WXaHAo.rst
new file mode 100644 (file)
index 0000000..7f2fb89
--- /dev/null
@@ -0,0 +1 @@
+PyOS_StdioReadline() no longer leaks memory when realloc() fails.
index 59db41ab1696319f58c84623647022be8a38aa21..537621402b8d1fc1ca2460b84a82f194c7db8e2d 100644 (file)
@@ -108,7 +108,7 @@ char *
 PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
 {
     size_t n;
-    char *p;
+    char *p, *pr;
     n = 100;
     if ((p = (char *)PyMem_MALLOC(n)) == NULL)
         return NULL;
@@ -140,17 +140,29 @@ PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
     n = strlen(p);
     while (n > 0 && p[n-1] != '\n') {
         size_t incr = n+2;
-        p = (char *)PyMem_REALLOC(p, n + incr);
-        if (p == NULL)
-            return NULL;
         if (incr > INT_MAX) {
+            PyMem_FREE(p);
             PyErr_SetString(PyExc_OverflowError, "input line too long");
+            return NULL;
+        }
+        pr = (char *)PyMem_REALLOC(p, n + incr);
+        if (pr == NULL) {
+            PyMem_FREE(p);
+            PyErr_NoMemory();
+            return NULL;
         }
+        p = pr;
         if (my_fgets(p+n, (int)incr, sys_stdin) != 0)
             break;
         n += strlen(p+n);
     }
-    return (char *)PyMem_REALLOC(p, n+1);
+    pr = (char *)PyMem_REALLOC(p, n+1);
+    if (pr == NULL) {
+        PyMem_FREE(p);
+        PyErr_NoMemory();
+        return NULL;
+    }
+    return pr;
 }