I am writing a C program where I want to trigger an exception such that the program crashes on Windows and invokes the Windows Error Reporting.
I thought, one good way to trigger a crash would be to divide by zero. However, when I try to do that, the compiler wouldn't compile the program and give the error: C2124.
Is there a way that I can force the compiler to compile the program and ignore the above divide by zero statement in the code?
Or should I find another way to crash my program? :)
#include <stdio.h>
int main(int argc, char **argv)
{
return 1/0;
}
abort
, defined in <stdlib.h>
is the preferred way to cause abnormal program termination. However, a solution to your specific intent to cause a divide-by-zero is to conceal the divisor from the compiler:
volatile int x = 0;
return 1/x;
The keyword volatile
tells the compiler that x
may be changed in ways unknown to the compiler. This prevents the compiler from knowing that it is zero, so the compiler must generate code to perform the division at run-time in case x
is changed to something other than zero.
Of course, the behavior of division by zero is not defined, so it is not guaranteed to cause program termination.
Also keep in mind that “If you lie to the compiler, it will get its revenge.” (Henry Spencer).