Suppose that a programmer forgot to initialize one of his automatic variables, and that he used its value, thereby invoking undefined behavior.
...
int i = 0, j;
...
printf("value of 'j': %d\n", j);
...
...
char buf[256];
fputs("Enter query:", stdout);
fgets(buf, sizeof(buf), stdin);
... //process input
... perform other tasks
The programmer noticed gibberish characters on the screen, and realized that his program is erroneous, but it did not crash and went on anyway.
Supposing after this point, the program prompts the user for input and is expected to process it, display results, and perform other tasks all of which are independent from the uninitialized variable, is the programmer encouraged to discontinue the use of the program, fix the error, recompile, and run? Will the remainder of the program be inconsistent?
Once a statement with undefined behaviour is reached, then the behaviour of the entire program is undefined.
Paradoxically, the behaviour of statements that have ran prior to that are undefined too.
Undefined behavior is merely the programming language's lack of guarantees. But of course there could be other things dictating the program behavior and even in deterministic ways, such as documented compiler extensions or OS and CPU behavior.
Therefore you cannot reason about undefined behavior from the programming language's point of view. The language will simply say that all bets are off and no behavior of the program is guaranteed.
With a specific system in mind, you can reason about what will happen though. If this is a meaningful thing to do is another story.
In your specific example, the typical system will probably just print some garbage indeed, and it is quite unlikely that the rest of the program will be affected. This isn't always the case of UB though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With