Skip to content

Commit

Permalink
Don't free-up file-descriptor of stdin/stdout/stderr
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mostafa-salmaan committed Mar 24, 2024
1 parent 6dc88ba commit 5ccc19b
Showing 1 changed file with 4 additions and 1 deletion.
5 changes: 4 additions & 1 deletion newlib/libc/tinystdio/bufio.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

0 comments on commit 5ccc19b

Please sign in to comment.