On Feb 26, 2:07*am, Philip Potter <p...@doc.ic.ac.ukwrote:
Quote:
I have a somewhat flippant question regarding undefined behaviour. Does
an operation which invokes undefined behaviour affect the whole program,
or are earlier statements guaranteed to execute correctly?
>
For example:
>
#include <stdio.h>
>
int main(void) {
* * int i;
* * printf("Hello, world!\n");
* * fflush(stdout);
* * i = i++; /* or some other undefined behaviour */
* * return 0;
>
}
>
Is the printf() statement guaranteed to execute? Is "Hello, world!\n"
guaranteed to be sent to stdout? Or could a conforming implementation
refuse to compile this program, or accept it and let loose nasal demons
without even greeting the world first?
Consider:
int main(void) {
int i;
printf("Hello, world!\n");
memset(&i, 0, 1000000000);
fflush(stdout);
return 0;
}
The previous printf() call completes successfully.
Then the memset() function call causes some horrible crash and we
never see the output.
That would be an example of subsequent undefined behavior affecting
previously correct code.
I do not think it is safe even after the fflush() call because :
"2 Ifstream points to an output stream or an update stream in which
the most recent
operation was not input, the fflush function causes any unwritten data
for that stream
to be delivered to the host environment to be written to the file;
otherwise, the behavior is
undefined."
So the data has been delivered to the operating system, but I do not
think it is a guarantee that it is written (indeed, for some operating
systems you must have a successful fsync() call or some such thing to
really guarantee delivery to the output stream).
So it is clear that we cannot depend on earlier code that is correct
to produce expected output after the introduction of undefined
behavior later in the program.