Skip to content

Commit 9ae513c

Browse files
committed
Issue python#18368: PyOS_StdioReadline() no longer leaks memory when realloc() fails.
1 parent fb29a16 commit 9ae513c

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ What's New in Python 3.3.3 release candidate 1?
1212
Core and Builtins
1313
-----------------
1414

15+
- Issue #18368: PyOS_StdioReadline() no longer leaks memory when realloc()
16+
fails.
17+
1518
- Issue #16741: Fix an error reporting in int().
1619

1720
- Issue #17899: Fix rare file descriptor leak in os.listdir().

Parser/myreadline.c

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ char *
112112
PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
113113
{
114114
size_t n;
115-
char *p;
115+
char *p, *pr;
116116
n = 100;
117117
if ((p = (char *)PyMem_MALLOC(n)) == NULL)
118118
return NULL;
@@ -135,17 +135,29 @@ PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
135135
n = strlen(p);
136136
while (n > 0 && p[n-1] != '\n') {
137137
size_t incr = n+2;
138-
p = (char *)PyMem_REALLOC(p, n + incr);
139-
if (p == NULL)
140-
return NULL;
141138
if (incr > INT_MAX) {
139+
PyMem_FREE(p);
142140
PyErr_SetString(PyExc_OverflowError, "input line too long");
141+
return NULL;
142+
}
143+
pr = (char *)PyMem_REALLOC(p, n + incr);
144+
if (pr == NULL) {
145+
PyMem_FREE(p);
146+
PyErr_NoMemory();
147+
return NULL;
143148
}
149+
p = pr;
144150
if (my_fgets(p+n, (int)incr, sys_stdin) != 0)
145151
break;
146152
n += strlen(p+n);
147153
}
148-
return (char *)PyMem_REALLOC(p, n+1);
154+
pr = (char *)PyMem_REALLOC(p, n+1);
155+
if (pr == NULL) {
156+
PyMem_FREE(p);
157+
PyErr_NoMemory();
158+
return NULL;
159+
}
160+
return pr;
149161
}
150162

151163

0 commit comments

Comments
 (0)