Can I assume that the stdlib function does not use errno?

I am looking at a piece of C code that is along the lines

void printerror(char *message) { printf ("There was an error: '%s'\n", message); switch (errno) { ... do stuff depending on errno } } 

I think this may be a problem, because printf can change errno between the input to the function and the achievement of switch . However, the printf manpage does not say anything about this by installing errno, so can I assume that he will never install it? Is there anything in the standards that guarantees which functions errno will and will not use?

+4
source share
3 answers

Any function can set errno, but only if it sets a nonzero value. The ANSI C specification states:

Errno is zero when the program starts, but it is never set to zero by any library function. * The value of errno can be set to a non-zero library function call, is there an error if the use of errno is not documented in the description in the standard.

* Therefore, a program that uses errno to check for errors should set it to zero before calling the library function, then check it before calling the library function later.

So, if you use errno, the best practice approach is to set the value to 0 just before the library call, which may fail, and read it immediately. In the above example, just add something like:

int localErrno = errno

immediately before the printf statement and use localErrno for your switch. This, of course, assumes that there are no library calls between the failed function and the printer call. If you need to save errno after an unsuccessful call and pass it to your print function. A.

+9
source

The C99 standard states the following:

Errno is zero when the program starts, but is never set by any library function. The errno value can be set to a nonzero value by calling the library function, whether or not an error exists, provided that the use of errno is not documented in the function description in this international standard.

So, in short, errno can be defined by any library function. To determine if this is really the case, the standard practice is to set it to zero before calling the function in question.

+3
source

In rare cases, printf may install errno. If you redirect stdout from your program to a file and the file system is full, printf () will return a negative number and set errno to ENOSPC (there is no space left on the device). You must make a local copy of errno before calling printf ().

+3
source

All Articles