C Program can find (via fopen) in gdb but not release (a.out)
Here's a C simple program, that reads a user input for a file location and prints the first line if such exists:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#include <errno.h>
int main() {
// init vars for user input, error checking
char file[PATH_MAX];
scanf("%s", file);
errno = 0;
FILE *contents = fopen(file, "r");
// debug, check if file exists and raises error if not
if (contents == NULL || errno != 0) {
printf("Error raised: %s", strerror(errno));
exit(1);
}
char example[1024] = "";
fgets(example, 1024, contents);
printf("%s", example);
// necessary closing of the stream
fclose(contents);
return 0;
}
Running the code on debug (gdb) works fine, I just input the file location that is on the same directory and it works fine. But running something like cat file.txt | ./a.out won't work; apparently, strerror() returns No such file or directory. I don't know enough of C to know how undefined behavior may come into play, but all I know is that it must have something to do with fopen.
Either way, I'm just hoping to either have an alternative working solution or to know why the debugger can do something an executable can't.