fclose: restore errno after call to free() if close() fails

This commit is contained in:
apio 2022-10-10 21:18:24 +02:00
parent 93f6be9319
commit 4f2b3ce5d1

View File

@ -1,3 +1,4 @@
#include <errno.h>
#include <fcntl.h>
#include <luna.h>
#include <stdio.h>
@ -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;
}