11

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?

Aziz Shaikh
  • 16,245
  • 11
  • 62
  • 79
FireAphis
  • 6,650
  • 8
  • 42
  • 63
  • 1
    Why don't you use `abort()` instead? Another option that can't be optimized away is writing to a NULL pointer. – Jan Hudec Feb 21 '13 at 06:41
  • @JanHudec In my case I needed specifically a division by zero. It was an embedded RT code and I wanted to reproduce system's behavior with a specific kind of failure. Things like these matter sometimes when you investigate bugs in embedded systems. – FireAphis Feb 26 '13 at 14:22

4 Answers4

17

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

volatile x = 1;
volatile y = 0;
volatile z = x / y;
GManNickG
  • 494,350
  • 52
  • 494
  • 543
14

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
NullUserException
  • 83,810
  • 28
  • 209
  • 234
2

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.

Chubsdad
  • 24,777
  • 4
  • 73
  • 129
-1

Typically, a divide by zero will throw an exception. If it is unhandled, it will break the program, but it will not crash.

Alexander Rafferty
  • 6,134
  • 4
  • 33
  • 55
  • That's a Microsoft-centric view - most environments do not translate machine exceptions such as divide by zero into C++ exceptions – Paul R Oct 05 '10 at 12:48
  • 1
    Nor VC++ does, IIRC on Windows divide by zero is by default a SEH exception. – Matteo Italia Oct 05 '10 at 12:51
  • It broke the program and gave me an unhandled exception when I compiled it. – Alexander Rafferty Oct 05 '10 at 13:03
  • @Alexander: do you mean a machine exception or a C++ exception ? – Paul R Oct 05 '10 at 14:22
  • 1
    @Matteo: from http://msdn.microsoft.com/en-us/library/6dekhbbc(VS.71).aspx : *"If the exception-declaration statement is an ellipsis (...), the catch clause handles any type of exception, including C exceptions and system- or application-generated exceptions such as memory protection, divide by zero, and floating-point violations."* This is the Microsoft-specific behaviour I was referring to. – Paul R Oct 05 '10 at 14:24
  • 1
    @Alexander: typically a divide by zero will invoke undefined behavior, on some architectures it may be trapped by the hardware, the C++ standard certainly doesn't guarantee anything afaik. – Matthieu M. Oct 05 '10 at 14:34