From 16c7952648d3a6a46965866511600c3dea954fef Mon Sep 17 00:00:00 2001 From: Stephen Heumann Date: Mon, 19 Feb 2024 22:30:15 -0600 Subject: [PATCH] fclose: close stream even if there is an error flushing buffered data. This can happen, e.g., if there is an IO error or if there is insufficient free disk space to flush the data. In this case, fclose should return -1 to report an error, but it should still effectively close the stream and deallocate the buffer for it. (This behavior is explicitly specified in the C99 and later standards.) Previously, ORCA/C effectively left the stream open in these cases. As a result, the buffer was not deallocated. More importantly, this could cause the program to hang at exit, because the stream would never be removed from the list of open files. Here is an example program that demonstrates the problem: /* * Run this on a volume with less than 1MB of free space, e.g. a floppy. * The fclose return value should be -1 (EOF), indicating an error, but * the two RealFreeMem values should be close to each other (indicating * that the buffer was freed), and the program should not hang on exit. */ #include #include #include #define BUFFER_SIZE 1000000 int main(void) { size_t i; int ret; printf("At start, RealFreeMem = %lu\n", RealFreeMem()); FILE *f = fopen("testfile", "wb"); if (!f) return 0; setvbuf(f, NULL, _IOFBF, BUFFER_SIZE); for (i = 0; i < BUFFER_SIZE; i++) { putc('x', f); } ret = fclose(f); printf("fclose return value = %d\n", ret); printf("At end, RealFreeMem = %lu (should be close to start value)\n", RealFreeMem()); } --- stdio.asm | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/stdio.asm b/stdio.asm index 8127991..64a7b54 100644 --- a/stdio.asm +++ b/stdio.asm @@ -83,16 +83,13 @@ stdfile equ 7 is this a standard file? phk plb - lda #EOF assume we will get an error - sta err ph4