Hacker News new | past | comments | ask | show | jobs | submit login

Functions using errno typically still use a return value of -1 to indicate an error has occurred, then errno just stores the specific error code. Otherwise, how do you even know that you need to check errno?



There are examples of such an ambiguity in the ISO C library itself.

In those situations, the application must begin by clearing errno to zero.

Then, it checks for a certain error value or values from the function which are ambiguous: they could be legit or indicate an error.

If one of those values occurs, and if errno is nonzero, then the error occurred.

This is how you deal with, for instance the strtol (string to long int) function. If there is a range error, strtol returns LONG_MIN or LONG_MAX. Those are also valid values in the range of long, but when no error has occurred, they are produced without errno being touched.

strtol can also return 0 in another error case, when the input is such that no conversion can be performed. ISO C doesn't require errno to be set to anything in this case, unfortunately. The case is distinguished from a legitimate zero by the original pointer to the string being stored in *endptr (if the caller specifies endptr that is not null).

ISO C and POSIX library functions do not reset errno to zero. They either leave it alone or set it to a nonzero value.

If you need to use the above trick and are working inside a C library function, you have to save the original errno value before storing a zero in it, and then put that value back if no error has happened.


You could always check errno and reset it to zero before any function call.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: