This is an example to illustrate my question which involves some much more complicated code that I can't post here.
#include <stdio.h> int main() { int a = 0; for (int i = 0; i < 3; i++) { printf("Hello\n"); a = a + 1000000000; } }
This program contains undefined behavior on my platform because a
will overflow on the 3rd loop.
Does that make the whole program have undefined behavior, or only after the overflow actually happens? Could the compiler potentially work out that a
will overflow so it can declare the whole loop undefined and not bother to run the printfs even though they all happen before the overflow?
(Tagged C and C++ even though are different because I'd be interested in answers for both languages if they are different.)
In contrast, the C standard says that signed integer overflow leads to undefined behavior where a program can do anything, including dumping core or overrunning a buffer. The misbehavior can even precede the overflow. Such an overflow can occur during addition, subtraction, multiplication, division, and left shift.
Buffer overflows cause undefined behavior—it's illegal to access memory outside any object.
Write a “C” function, int addOvf(int* result, int a, int b) If there is no overflow, the function places the resultant = sum a+b in “result” and returns 0. Otherwise it returns -1. The solution of casting to long and adding to find detecting the overflow is not allowed.
Most languages have a terrible stack overflow story. For example, in C, if you use too much stack, your program will exhibit “undefined behavior”, which if you are lucky means that it will crash.
If you're interested in a purely theoretical answer, the C++ standard allows undefined behaviour to "time travel":
[intro.execution]/5:
A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input. However, if any such execution contains an undefined operation, this International Standard places no requirement on the implementation executing that program with that input (not even with regard to operations preceding the first undefined operation)
As such, if your program contains undefined behaviour, then the behaviour of your whole program is undefined.
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