Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cause an intentional division by zero?

For testing reasons I would like to cause a division by zero in my C++ code. I wrote this code:

int x = 9;
cout << "int x=" << x;
int y = 10/(x-9);
y += 10;

I see "int =9" printed on the screen, but the application doesn't crash. Is it because of some compiler optimizations (I compile with gcc)? What could be the reason?

like image 549
FireAphis Avatar asked Oct 05 '10 12:10

FireAphis


People also ask

How do you divide by zero?

0 Divided by a Number 0a=0 Dividing 0 by any number gives us a zero. Zero will never change when multiplying or dividing any number by it. Finally, probably the most important rule is: a0 is undefined You cannot divide a number by zero! If you want to know why this is check out this awesome video by Numberphile!

Why can't we divide by zero?

The short answer is that 0 has no multiplicative inverse, and any attempt to define a real number as the multiplicative inverse of 0 would result in the contradiction 0 = 1.

What happens if you divide by 0 C++?

Dividing a number by Zero is a mathematical error (not defined) and we can use exception handling to gracefully overcome such operations. If you write a code without using exception handling then the output of division by zero will be shown as infinity which cannot be further processed.

Why any number divided by zero is undefined?

Because what happens is that if we can say that zero, 5, or basically any number, then that means that that "c" is not unique. So, in this scenario the first part doesn't work. So, that means that this is going to be undefined. So zero divided by zero is undefined.


3 Answers

Make the variables volatile. Reads and writes to volatile variables are considered observable:

volatile x = 1;
volatile y = 0;
volatile z = x / y;
like image 173
GManNickG Avatar answered Oct 03 '22 03:10

GManNickG


Because y is not being used, it's getting optimized away.
Try adding a cout << y at the end.

Alternatively, you can turn off optimization:

gcc -O0 file.cpp
like image 28
NullUserException Avatar answered Oct 03 '22 03:10

NullUserException


Division by zero is an undefined behavior. Not crashing is also pretty much a proper subset of the potentially infinite number of possible behaviors in the domain of undefined behavior.

like image 32
Chubsdad Avatar answered Oct 03 '22 04:10

Chubsdad