Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 387 Vote(s) - 3.48 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What is wrong with INT32_MIN/-1?

#1
John Regehr's blog post [*A Guide to Undefined Behavior in C and C++, Part 1*](

[To see links please register here]

) contains the following "safe" function for "performing integer division without executing undefined behavior":

int32_t safe_div_int32_t (int32_t a, int32_t b) {
if ((b == 0) || ((a == INT32_MIN) && (b == -1))) {
report_integer_math_error();
return 0;
} else {
return a / b;
}
}


[1]:

[To see links please register here]


I'm wondering what is wrong with the division (a/b) when a = INT32_MIN and b = -1. Is it undefined? If so why?
Reply

#2
Because INT32_MIN is defined as (-INT32_MAX-1) = -(INT32_MAX+1) and when divided by -1, this would be (INT32+MAX) => there is an integer overflow. I must say, that is a nice way to check for overflows. Thoughtfully written code. +1 to the developer.
Reply

#3
This is because `int32_t` is represented using two's-complement, and numbers with `N` bits in two's-complement range from `−2^(N−1)` to `2^(N−1)−1`. Therefore, when you carry out the division, you get: `-2^(31) / -1 = 2^(N-1)`. Notice that the result is larger than `2^(N-1)-1`, meaning you get an overflow!
Reply

#4
I think it's because the absolute value of INT32_MIN is 1 larger than INT32_MAX. So INT32_MIN/-1 actually equals INT32_MAX + 1 which would overflow.

So for 32-bit integers, there are 4,294,967,296 values.<br />
There are 2,147,483,648 values for negative numbers (-2,147,483,648 to -1).<br />
There is 1 value for zero (0).<br />
There are 2,147,483,647 values for positive numbers (1 to 2,147,483,647) because 0 took 1 value away from the positive numbers.<br />
Reply

#5
The other posters are correct about the causes of the overflow. The implication of the overflow on most machines is that INT_MIN / -1 => INT_ MIN. The same thing happens when multiplying by -1. This is an unexpected and possibly dangerous result. I've seen a fixed-point motor controller go out of control because it didn't check for this condition.
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through