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 47f256b1ff51dd383ebc4869d94c0e638057f167 Mon Sep 17 00:00:00 2001 From: rosenrost <52100845+rosenrost@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:39:38 +0100 Subject: [PATCH 2/2] Always write to the end of the file in append mode Streams opened with "a" or "a+" only seeked to the end of the file once in fopen(). After an fseek() or reading in "a+" mode, data was written into the middle of the file. fwrite() now moves to the end of the file before every write of an append mode stream. --- sources/fwrite.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/sources/fwrite.c b/sources/fwrite.c index 021fe1a..9126067 100644 --- a/sources/fwrite.c +++ b/sources/fwrite.c @@ -20,6 +20,12 @@ size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) n = size * nmemb; + if (stream->__mode.__append) + { + /* in append mode every write goes to the end of the file, even after fseek() */ + (void)Fseek(0, (int)FILE_GET_HANDLE(stream), SEEK_END); + } + #ifdef STDIO_MAP_NEWLINE if (stream->__mode.__binary) {