perror generating unexpected errno value

1.1k Views Asked by At

I am experiencing an unexpected value of errno when using perror with glibc. When an non-existent file is specified as arg[1] it prints Error: 2 ( which isENOENT) as expected. However when the perror line below is uncommented it throws error 22 (EINVAL) no matter what I pass it. Can anyone please explain why this is getting set?

EDIT: Looks like this is some sort of Eclipse bug. The IDE seems to be causing perror to throw some sort of error, the program works perfectly on the command line, and works perfectly when a correct file is specified in the argument list in Eclipse. It fails incorrectly when run inside of Eclipse.

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main(int argc, char *argv[]) {
FILE *input_file;
input_file = fopen(argv[argc - 1], "r");
if (!input_file) {
 // perror(argv[argc-1]);
    fprintf(stderr, "Error: %d\n", errno);
    return (EXIT_FAILURE);
}
else {
    fclose(input_file);
}
return (EXIT_SUCCESS);
}
3

There are 3 best solutions below

2
On BEST ANSWER

You can't rely on the value of errno after calling into other library functions, in other words your call to perror() itself may be modifying the value of errno You need to save it in a temporary variable if you want to be able to use it after calls into other library procedures.

if (!input_file) {
    int err = errno;
    perror(argv[argc-1]);
    fprintf(stderr, "Error: %d\n", err);
    return (EXIT_FAILURE);
}
1
On

Your program works as expected for me here:

$ ./app fkjhsf
Error: 2

and with the perror() call uncommented:

$ ./app asdkfljh
asdkfljh: No such file or directory
Error: 2

Maybe the perror() call is changing your errno for some reason? What operating system/compiler/library versions are you using?

1
On

He's likely running the program without any arguments.

If so, "argv[argc - 1]" will evaluate to garbage.

There should be code to make sure that "argc-1" is within a valid range.