【问题标题】:Why this little program output True? Is GCC's overflow protection?为什么这个小程序输出True? GCC的溢出保护吗?
【发布时间】:2021-03-28 07:42:29
【问题描述】:
#include<stdio.h>

void main(){

    int x = 0x80000000;
    if((x-1)<1)
        printf("True");
    else
        printf("False");

}

这是来自csapp practice 2.44,如果这是编译器的操作,如何关闭它?

【问题讨论】:

  • “关闭”是什么意思?
  • @EricPostpischil,关闭编译器的优化操作。

标签: c gcc overflow


【解决方案1】:

假设 int 是 32 位的,则常量 0x80000000 超出了 int 的范围,并且具有 unsigned int 类型。当用于初始化int 时,它会以实现定义的方式进行转换。对于 gcc,该转换导致 x 的值为 -231(其表示恰好是 0x80000000),这是它可以容纳的最小值。

然后当您尝试计算x-1 时,它会导致undefined behavior 的有符号整数溢出。例如,如果我在 gcc 4.8.5 下使用 -O0-O1 编译此代码,我会得到“False”作为输出,如果我使用 -O2-O3 编译它会输出“True”。

【讨论】:

  • 在gcc中,'-o0','-o1','o2'表示不同的优化级别,当我使用'-o0'时,它返回false,问题已解决,谢谢。
  • @frozen 很高兴我能帮上忙。如果您觉得有用,请随时 accept this answer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
相关资源
最近更新 更多