Created
May 23, 2014 08:42
-
-
Save ohe/7f2b9a3e4e4e32087ba8 to your computer and use it in GitHub Desktop.
Why you should (sometimes) reset errno manually!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <limits.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <assert.h> | |
int main(void) { | |
unsigned long number = -1; | |
char *endptr = NULL; | |
/* Checking that errno is set to 0 at the initialisation of our program */ | |
assert(errno == 0); | |
/* Trying to open a file with an invalid mode */ | |
/* This set errno to EINVAL value */ | |
fopen("something", "invalid"); | |
assert(errno == EINVAL); | |
/* the missing line! */ | |
/* Uncomment it to fix the behavior of this snippet */ | |
/* errno = 0;*/ | |
number = strtoul("0", &endptr, 0); | |
/* Trying to catch errors according to the man page of strtoul */ | |
/* Extract of the manpage: | |
* The strtoul(), strtoull(), strtoumax() and strtouq() functions return | |
* either the result of the conversion or, if there was a leading minus | |
* sign, the negation of the result of the conversion, unless the origi- | |
* nal (non-negated) value would overflow; in the latter case, strtoul() | |
* returns ULONG_MAX, strtoull() returns ULLONG_MAX, strtoumax() returns | |
* UINTMAX_MAX, and strtouq() returns ULLONG_MAX. In all cases, errno | |
* is set to ERANGE. If no conversion could be performed, 0 is returned | |
* and the global variable errno is set to | |
* EINVAL (the last feature is not portable across all platforms). | |
*/ | |
if ((number == 0 && errno == EINVAL) || (number == ULONG_MAX && errno == ERANGE)) { | |
printf("wrong error detected\n"); | |
} else { | |
printf("computation succeeded\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment