Which values of x and y will cause a crash with some C compilers?
int f(int x, int y) {
return (y==0) ? 0 : (x/y);
}
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It only takes a minute to sign up.
Sign up to join this communityWhich values of x and y will cause a crash with some C compilers?
int f(int x, int y) {
return (y==0) ? 0 : (x/y);
}
-2147483648 (INT_MIN) and -1
#include <stdio.h>
#include <limits.h>
int f(int x, int y) {
return (y==0) ? 0 : (x/y);
}
int main() {
int r = f(INT_MIN, -1);
printf("%d\n", r);
return 0;
}
$ gcc -Wall division.c && ./a.out # => zsh: floating point exception ./a.out
The right answer is already given, but I immediately thought about Microsoft Pex.
Pex automatically generates test suites with high code coverage. Right from the Visual Studio code editor, Pex finds interesting input-output values of your methods, which you can save as a small test suite with high code coverage. Microsoft Pex is a Visual Studio add-in for testing .NET Framework applications
After adding your puzzle in the sandbox site, it finds the answer in a few seconds, the same as eregons answer. (click ask pex)
Note: it does it in C#, but the language is not really relevant.
(x/y)
and know that INT_MIN
, -1
, 0
etc. are all problem cases for that expression, and try to reverse engineer a way to produce those values at the time of evaluation.
\$\endgroup\$