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; }