From 4f2b3ce5d10b3032462b33802e9a9232a3dff949 Mon Sep 17 00:00:00 2001 From: apio Date: Mon, 10 Oct 2022 21:18:24 +0200 Subject: [PATCH] fclose: restore errno after call to free() if close() fails --- libs/libc/src/file.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/libs/libc/src/file.cpp b/libs/libc/src/file.cpp index 8bc63ef1..6d2458e0 100644 --- a/libs/libc/src/file.cpp +++ b/libs/libc/src/file.cpp @@ -1,3 +1,4 @@ +#include #include #include #include @@ -9,9 +10,15 @@ extern "C" int fclose(FILE* stream) { int status = close(stream->fd); - free(stream); // We do not want to leak memory. man fclose(3) says that whether fclose() fails or not, any - // further operation on the stream results in undefined behavior. So we are free to free the - // stream. + if (status < 0) + { + int savederr = errno; + free(stream); // We do not want to leak memory. man fclose(3) says that whether fclose() fails or not, any + // further operation on the stream results in undefined behavior. So we are free to free the + // stream. + errno = savederr; // free might reset errno. We don't want that. + } + else { free(stream); } return status; }