【发布时间】:2012-10-13 01:01:37
【问题描述】:
我正在尝试使用errno 来检测我是否执行了导致溢出的操作。然而,虽然我写了一个故意溢出的函数,errno == ERANGE 是假的。这是怎么回事?
代码如下:
#include <stdio.h>
#include <errno.h>
int main(int argc, char* argv[]) {
unsigned char c = 0;
int i;
for (i = 0; i< 300; i++) {
errno = 0;
c = c + 1;
if (errno == ERANGE) {// we have a range error
printf("Overflow. c = %u\n", c);
} else {
printf("No error. c = %u\n", c);
}
}
return 0;
}
我预计这会在我们将 1 加到 255 时出现溢出错误,但没有错误。这是(截断的)输出:
No error. c = 245
No error. c = 246
No error. c = 247
No error. c = 248
No error. c = 249
No error. c = 250
No error. c = 251
No error. c = 252
No error. c = 253
No error. c = 254
No error. c = 255
No error. c = 0
No error. c = 1
No error. c = 2
No error. c = 3
No error. c = 4
No error. c = 5
No error. c = 6
No error. c = 7
No error. c = 8
No error. c = 9
有人可以解释为什么它没有检测到错误,以及我如何更改它或以其他方式制作一个可以检测我的值是否溢出的函数?注意:最终我想用long ints 来做这件事,所以不可能简单地将它转换成更大的数据类型。
编辑:
我已经找到了一些简单的函数来分别检测整数数据类型的加法和乘法溢出。它没有涵盖所有情况,但涵盖了很多情况。
乘法:
int multOK(long x, long y)
/* Returns 1 if x and y can multiply without overflow, 0 otherwise */
{
long p = x*y;
return !x || p/x == y;
}
签名添加:
int addOK(long x, long y)
/* Returns 1 if x and y can add without overflow, 0 otherwise */
{
long sum = x+y;
int neg_over = (x < 0) && (y < 0) && (sum >= 0);
int pos_over = (x >= 0) && (y >= 0) && (sum < 0);
return !neg_over && !pos_over;
}
无符号加法:
int unsignedAddOK(unsigned long x, unsigned long y)
/* Returns 1 if x and y can add without overflow, 0 otherwise */
{
unsigned long sum = x+y;
return sum > x && sum > y;
}
【问题讨论】:
-
简单地递增不会抛出错误,因此不会设置errno。 函数(例如
strtod)设置errno。 -
另外,查看
<limits.h>以及this related question 可能会有所帮助。 -
您可能希望使用一种检查整数溢出的语言(例如带有
checked的 Ada 或 C#)或透明地支持任意精度算术的语言(例如 Python、Lisp、Haskell 等。 )