From 16f080265d64c718558edcf92ce0076aaa3fe4c0 Mon Sep 17 00:00:00 2001 From: rosenrost <52100845+rosenrost@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:17:08 +0100 Subject: [PATCH 1/2] Fix division by zero in fread() and fwrite() Both functions divided the number of transferred bytes by size to compute the number of items, which crashed with a division by zero when called with size == 0. Return 0 early if size or nmemb is 0, as required by the C standard. --- sources/fread.c | 10 ++++++++-- sources/fwrite.c | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/sources/fread.c b/sources/fread.c index 15f6239..46af9f8 100644 --- a/sources/fread.c +++ b/sources/fread.c @@ -5,8 +5,14 @@ size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) { - size_t bytes = size * nmemb; - long rc = Fread(FILE_GET_HANDLE(stream), bytes, ptr); + size_t bytes; + long rc; + + if (size == 0 || nmemb == 0) + return 0; + + bytes = size * nmemb; + rc = Fread(FILE_GET_HANDLE(stream), bytes, ptr); if (rc < 0) { diff --git a/sources/fwrite.c b/sources/fwrite.c index 92e7761..021fe1a 100644 --- a/sources/fwrite.c +++ b/sources/fwrite.c @@ -10,11 +10,17 @@ size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) { long rc; - size_t n = size * nmemb; - + size_t n; #ifdef STDIO_MAP_NEWLINE int fd = (int)FILE_GET_HANDLE(stream); +#endif + + if (size == 0 || nmemb == 0) + return 0; + n = size * nmemb; + +#ifdef STDIO_MAP_NEWLINE if (stream->__mode.__binary) { rc = Fwrite(fd, n, ptr); From 2d6c6b58ef62a7889e79917cb291006d342fbdcd Mon Sep 17 00:00:00 2001 From: rosenrost <52100845+rosenrost@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:39:57 +0100 Subject: [PATCH 2/2] Return the ungetc() character from fread() fread() read directly from the file handle and ignored a character pushed back with ungetc(), which was then returned by a later fgetc() out of order. --- sources/fread.c | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/sources/fread.c b/sources/fread.c index 46af9f8..c4b87b7 100644 --- a/sources/fread.c +++ b/sources/fread.c @@ -6,24 +6,35 @@ size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream) { size_t bytes; + size_t got = 0; long rc; if (size == 0 || nmemb == 0) return 0; bytes = size * nmemb; - rc = Fread(FILE_GET_HANDLE(stream), bytes, ptr); + + if (stream->__pushback != EOF) + { + /* a character pushed back by ungetc() comes first */ + *(unsigned char *)ptr = (unsigned char)stream->__pushback; + stream->__pushback = EOF; + ptr = (unsigned char *)ptr + 1; + --bytes; + ++got; + } + + rc = bytes > 0 ? Fread(FILE_GET_HANDLE(stream), bytes, ptr) : 0; if (rc < 0) { stream->__error = 1; __set_errno(-rc); - rc = 0; } else { - if (rc < bytes) + if ((size_t)rc < bytes) stream->__eof = 1; - rc /= size; + got += rc; } - return rc; + return got / size; }