From dc2de136eda7ef847ce39e445224dde56b3ab68a Mon Sep 17 00:00:00 2001 From: Mostafa Salman Date: Sun, 24 Mar 2024 12:09:14 +0200 Subject: [PATCH] Don't free-up file-descriptor of stdin/stdout/stderr stdout, stdin and stderr are statically allocated at tinystdio/posixiob_stdout.c, tinystdio/posixiob_stdin.c and tinystdio/posixiob_stderr.c respectively. and the issue here is that the current implementation of `fclose()` frees the allocated memory for the stream file. When we call `fclose(stdout)` it tries to free an unallocated memory for _stdout_, so it frees a wrong pointer and saves it as a free heap space, then when trying to use this memory it causes memory corruption. So, we shouldn't free the memory if the stream is stdin, stdout or stderr. --- newlib/libc/tinystdio/bufio.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/newlib/libc/tinystdio/bufio.c b/newlib/libc/tinystdio/bufio.c index 467a311a9a..af769e6e85 100644 --- a/newlib/libc/tinystdio/bufio.c +++ b/newlib/libc/tinystdio/bufio.c @@ -307,7 +307,10 @@ __bufio_close(FILE *f) /* Don't close stdin/stdout/stderr fds */ if (bf->fd > 2) (bf->close)(bf->fd); - free(f); + + /* Don't free memory if the stream is stdin/stdout/stderr */ + if ((f != stdin) && (f != stdout) && (f != stderr)) + free(f); return ret; }