整数溢出一则

1299阅读 0评论2012-02-23 zboom
分类:C/C++

先从一段计算百分比的代码说起。

1 #include
2 int main()
3 {
4     int count = 1;
5     int total = 11;
6     float percent = 0;
7     percent = (float)(count * 100 )/total;
8     printf("percentage is %.2f\n",percent);
9     return 0;
10 }

[root@localhost test]# gcc test_float2.c             
[root@localhost test]# ./a.out
percentage is 9.09

OK,结果正确,貌似没有问题,其实不然,我们把数字放大再看看结果吧。

4     int count = 100000000; //一亿
5     int total = 1100000000; //11亿

percentage is 1.28

奇怪了,同样的比例,为啥结果不一样呢?细心的朋友肯定早就发现了,第7行count先乘了100,当count*100值大于2147483647(21亿多)时,发生了整形溢出。

修改成:

7     percent = ((float)count/total)*100;

percentage is 9.09

另外,为什么发生溢出的结果是1.28呢,让我们来算一下:

100亿对应的二进制数是:10 01010100 00001011 11100100 00000000,一个34位,溢出了两位,符号位为0,所以溢出之后得到的结果是01010100 00001011 11100100 00000000,换算成十进制数是1410065408,这个数除以1100000000,取两位有效数字,得1.28。

上一篇:Linux 内核代码赏析与应用(三)-链表API之应用
下一篇:整数溢出漏洞与预防