IT技术博客大学习 共学习 共进步
全部 移动开发 后端 数据库 AI 算法 安全 DevOps 前端 设计 开发者

编写安全代码:再论整数类型转换

kernelchina blogs 2012-06-20 22:50:58 累计浏览 4,008 次
本机暂存
前几天看C99标准,写了两篇关于整数提升的博文,http://blog.chinaunix.net/space.php?uid=23629988&do=blog&id=2938697在这篇的评论中,pragma朋友提出了一个问题。经过了重新阅读C99,和别人讨论,外加思考,得到了答案。这再次加深了我对整数提升的理解,所以需要进一步总结一下这个问题。
先看看pragma提出的问题吧。

  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #define PRINT_COMPARE_RESULT(a, b) \
  4.     if (a > b) { \
  5.         printf( #a " > " #b "\n"); \
  6.     } \
  7.     else if (a < b) { \
  8.         printf( #a " < " #b "\n"); \
  9.     } \
  10.     else { \
  11.         printf( #a " = " #b "\n" ); \
  12.     }
  13. int main()
  14. {
  15.     signed int a = -1;
  16.     unsigned int b = 2;
  17.     signed short c = -1;
  18.     unsigned short d = 2;
  19.     PRINT_COMPARE_RESULT(a,b);
  20.     PRINT_COMPARE_RESULT(c,d);
  21.     return 0;
  22. }
输出结果为

  1. [root@Lnx99 test]#./a.out
  2. a > b
  3. c < d
为什么将int换为short后,结果就不一样了呢?
在C99标准中算数运算中有两种conversion,一个是integer promotion,另外一个是usual arithmetic conversions。在前面的博文中,我研究的是第二种,并将其理解为integer promotion,其实是不准确的。
下面是C99中关于第一种integer promotion的描述:
If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.
——在C99的上下文,这个integer promotion发生在算术运算的时候。

而C99关于usual arithmetic conversions,参加我这篇博文:http://blog.chinaunix.net/space.php?uid=23629988&do=blog&id=2938697

这样的话,也就是说在算术运算中,会涉及两种integer conversion。上面的测试代码的结果,也是由此而来。
下面开始分析:
对于a和b来说,integer promotion相当于不起作用,所以只进行usual arithmetic conversion,根据规则,将a转为unsigned int,所以a>b。
对于c和d来说,首先integer promotion会起作用,c和d都会转为int型,也就是说相当于int c = -1,int d = 2;然后进行usual arithmetic conversion,因为两者此时都为int型,那么自然结果是c < d了。
现在答案已经清晰了,但是却让我感到一阵阵忐忑,因为这样的整数转换规则太容易让人犯错了。对于我们来说,虽然已经比较明晰两个规则,但是在代码中还是要尽量避免有符号数和无符号数的比较。如果无法避免,为了清楚的表明自己的目的,最好使用强制类型转换。

同分类推荐文章

  1. 绿盟科技《APT组织研究年鉴》(2026 版)正式发布 (2026-06-16 20:21:10)
  2. 【已复现】Linux内核Fragnesia权限提升漏洞(CVE-2026-46300) (2026-06-15 10:53:58)
  3. 企业文档安全最佳实践(二):给文档上“身份证”——手动标密与智能自动标密 (2026-06-12 17:18:33)

查看更多 安全 文章 →