模量溢出? [英] Does modulus overflow?

查看:165
本文介绍了模量溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道(INT_MIN / -1)溢出,但是(INT_MIN%-1)不会溢出。至少这是在两个编译器中发生的,一个是前c ++ 11(VC ++ 2010)和另一个后c ++ 11 GCC 4.8.1

  int x = INT_MIN; 
cout<< x / -1 < endl
cout<< x%-1<< endl

赠送:

 code> -2147483648 
0

这是定义的行为标准,定义?
也有有任何其他情况下,分区操作会溢出?
并且是否存在模运算符溢出的情况?

解决方案

根据 CERT C ++安全编码标准模数可以可以溢出它说:


[...]当被除数等于有符号整数类型的最小(负)值并且除数等于-1时,在模运算期间可能发生溢出。


,他们推荐以下检查风格以防止溢出:

  signed long sl1,sl2,result; 

/ *初始化sl1和sl2 * /

if((sl2 == 0)||((sl1 == LONG_MIN)& 1))){
/ *句柄错误条件* /
}
else {
result = sl1%sl2;
}

C ++草稿标准 5.6 乘法 binary /运算符产生商,二进制%运算符产生第一个表达式除以秒的余数。如果/或%的第二个操作数为零,则该行为是未定义的。对于积分操作数,/运算符产生代数商,其中任何小数部分被丢弃; 81 如果商a / b在结果类型中可表示,(a / b)* b + a%b等于a;


C版本的CERT文档提供了一些更多的洞察如何在某些平台上工作,在某些情况下 INT_MIN%-1 可能产生浮点异常



的溢出与上述的逻辑相同。


I know that (INT_MIN / -1) overflows, but (INT_MIN % -1) does not. At least this is what happens in two compilers, one pre-c++11 (VC++ 2010) and the other post-c++11 GCC 4.8.1

int x = INT_MIN;
cout << x / -1 << endl; 
cout << x % -1 << endl;

Gives:

-2147483648
0

Is this behavior standard defined or this is implementation defined? Also is there ANY OTHER case where the division operation would overflow? and is there any case where the modulus operator would overflow?

解决方案

According to CERT C++ Secure Coding Standard modulus can can overflow it says:

[...]Overflow can occur during a modulo operation when the dividend is equal to the minimum (negative) value for the signed integer type and the divisor is equal to -1.

and they recommend the follow style of check to prevent overflow:

signed long sl1, sl2, result;

/* Initialize sl1 and sl2 */

if ( (sl2 == 0 ) || ( (sl1 == LONG_MIN) && (sl2 == -1) ) ) {
  /* handle error condition */
}
else {
  result = sl1 % sl2;
}

The C++ draft standard section 5.6 Multiplicative operators paragraph 4 says(emphasis mine):

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. For integral operands the / operator yields the algebraic quotient with any fractional part discarded;81 if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a; otherwise, the behavior of both a/b and a%b is undefined.

The C version of the CERT document provides some more insight on how % works on some platforms and in some cases INT_MIN % -1 could produce a floating-point exception.

The logic for preventing overflow for / is the same as the above logic for %.

这篇关于模量溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆