问题
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?
回答1:
Make the variables volatile. Reads and writes to volatile variables are considered observable:
volatile x = 1;
volatile y = 0;
volatile z = x / y;
回答2:
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
回答3:
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.
回答4:
Typically, a divide by zero will throw an exception. If it is unhandled, it will break the program, but it will not crash.
来源:https://stackoverflow.com/questions/3863656/how-to-cause-an-intentional-division-by-zero