I tried to open a file in a non existing directory in C++ and for some reason my application didn't crash. I find that a bit "weird" because I'm used to C, where the equivalent program does crash. Here is my C++ version followed by the equivalent C version:
$ cat main.cpp
#include <fstream>
int main(int argc, char **argv)
{
std::ofstream f("/home/oren/NON_EXISTING_DIR/file.txt");
f << "lorem ipsum\n";
f.close();
printf("all good\n");
}
$ g++ main.cpp -o main
$ ./main
all good
When I try the equivalent thing with C I get a segfault:
$ cat main.c
#include <stdio.h>
int main(int argc, char **argv)
{
FILE *fl = fopen("/home/oren/NON_EXISTING_DIR/file.txt","w+t");
fprintf(fl,"lorem ipsum\n");
fclose(fl);
printf("all good\n");
}
$ gcc main.c -o main
$ ./main
Segmentation fault (core dumped)
Why is that?
"I'm used to C", but then "[...] in C++" - well, C++
is not C
, but that's irrelevant here. First, have a look at this - writes to an unopened stream (which is the case here) are ignored after setting the failbit.
In your C
example, however, the problem is that if fopen
fais, it returns a NULL
pointer. Then you pass it to fprintf
. That's where the Undefined Behaviour1 happens. No such thing in the C++
example.
1Do note that the C
example is not guaranteed to SEGFAULT. Undefined behaviour is undefined.