On Fri, Nov 08, 2019 at 04:34:10PM +0200, Eli Zaretskii wrote: > > Libc functions are free to call other functions internally, > > and such internal calls may fail where the outer level call > > does not fail. So even if a libc function does not return > > an error, errno can have changed. > > That would be a bug in libc, I think. Its functions should save and > restore errno if other functions they call error out without causing > the calling function to fail.
% man 3 errno ... A common mistake is to do if (somecall() == -1) { printf("somecall() failed\n"); if (errno == ...) { ... } } where errno no longer needs to have the value it had upon return from somecall() (i.e., it may have been changed by the printf(3)). If the value of errno should be preserved across a library call, it must be saved: if (somecall() == -1) { int errsv = errno; printf("somecall() failed\n"); if (errsv == ...) { ... } } That was the Linux man page. Here is the POSIX man page: ... The value in errno is significant only when the return value of the call indicated an error (i.e., -1 from most system calls; -1 or NULL from most library functions); a function that succeeds is allowed to change errno. Andries