Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a part of the program exhibits undefined behavior, would it affect the remainder of the program?

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?

like image 761
machine_1 Avatar asked Feb 05 '18 13:02

machine_1


2 Answers

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.

like image 196
Bathsheba Avatar answered Oct 17 '22 07:10

Bathsheba


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.

like image 2
Lundin Avatar answered Oct 17 '22 09:10

Lundin