刷 csapp 碰到的一道的练习题.

发布于 2022-09-02 11:57:52 字数 245 浏览 26 评论 0

书中要求写一个带有两个整形参数的函数,要求判断是否会发生溢出,书中给出了一段错误代码,问我为什么这么判断是错误的,我只能举出反例,却说不上为什么.代码如下:

#include<stdio.h>

int tadd_ok(int x, int y){
  int sum = x + y;
  return (sum - x == y) && (sum - y == x);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

云胡 2022-09-09 11:57:53

我自己尝试着解释了一下, 不知道正不正确

/*
  The aim of this function is to judge if the addition of two number
  will result overflow. If not return 1 else 0.
 */
int tadd_ok(int x, int y){
  int sum = x + y;
  return (sum - x == y) && (sum - y == x);
}

/*
  The is the reason why this is wrong : 
there are two situations that will cause overflow.
 assume the int is w-bit-long.

  1. two negtive number and get a positive number.
  In this case : x + y < -2^(w-1)   => since the minium number of int is -2^(w-1)
  so in fact sum =  (x + y + 2^w)  => for example -1 + -8 will get 7 if w = 4.
  so when you use sum - x you will get (y + 2^w) % 2^w result y
  (when the value is bigger than 2^w) it's the same for sum -  y.

  2. two positive number and get a negtive number.
  In this case : x + y > 2^(w-1) - 1 => since the maximum number of int is 2^(w-1) - 1
  so sum = (x + y - 2^w => for example 5 + 5 will get -6 if w = 4
  so when you use sum - x you will get (y - 2^w) since y < 2^(w-1) - 1 so the value will be
  smaller than -1 - 2(w-1) which is also over flow so in fact it is (y - 2^w) % 2^w == y.

 */
顾挽 2022-09-09 11:57:53

上述代码不能用来检测有符号数溢出,补码加会形成一个阿贝尔群,因此表达式(x+y)-x求值得到 y,无论加法是否溢出,而 (x+y)-y 总是会求值得到 x
证明过程:
http://hi.csdn.net/attachment...

蝶…霜飞 2022-09-09 11:57:53

整形加法本来就有可能溢出啊

若无相欠,怎会相见 2022-09-09 11:57:52

难道不是永远返回非0值

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文