# Which Numbers Would Crash this Function?

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);
}

• Since C's ternary operator shortcuts, I would say none would. This question doesn't seem to fit the format for this site, which is focused on program puzzles and code golf. See the faq for details codegolf.stackexchange.com/faq. – Steven Rumbalski Jan 12 '12 at 14:48
• This isn't code golf, but is a puzzle. There is an answer, and it's just a couple of numbers. – ugoren Jan 12 '12 at 14:51
• I stand corrected. – Steven Rumbalski Jan 12 '12 at 14:59
• Actually, judging by the K&R book, this function really must never crash. But by the ANSI C standard, the behavior in the particular crashing case is undefined, and with x86 compilers it crashes. – ugoren Jan 12 '12 at 15:05
• @dmckee, If you give the right answer, you're the winner. What cretirion could be more clear and objective? There's only one answer (or do you have another example?) – ugoren Jan 12 '12 at 18:10

-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

• Indeed. Though this should give a warning, because 2147483648 isn't a valid integer. – ugoren Jan 12 '12 at 14:57
• Yes, that's why I used INT_MIN after, to use a valid int. I guess the reason is 2147483648 is not a valid int, since INT_MAX is 2^31-1 with 32-bit int. – eregon Jan 12 '12 at 14:59
• Ah. Two's complement. I missed that. – Steven Rumbalski Jan 12 '12 at 15:00
• Yes, it should compile cleanly with INT_MIN (which is -2147483648). – ugoren Jan 12 '12 at 15:02

• Hopefully it's a little more clever than that. It might look at (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. – Clueless Jan 18 '12 at 21:01