Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

At what point in the loop does integer overflow become undefined behavior?

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.)

like image 705
jcoder Avatar asked Oct 07 '16 10:10

jcoder


People also ask

Why is integer overflow undefined behavior?

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.

Is a buffer overflow undefined behavior?

Buffer overflows cause undefined behavior—it's illegal to access memory outside any object.

How do you check if an integer is overflow?

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.

Is stack overflow undefined behavior?

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.


1 Answers

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.

like image 133
TartanLlama Avatar answered Oct 06 '22 01:10

TartanLlama