C ++中的整数溢出是多么的灾难性? [英] How disastrous is integer overflow in C++?

查看:249
本文介绍了C ++中的整数溢出是多么的灾难性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想知道如何灾难性的整数溢出真的是。采取以下示例程序:

I was just wondering how disastrous integer overflow really is. Take the following example program:

#include <iostream>

int main()
{
    int a = 46341;
    int b = a * a;
    std::cout << "hello world\n";
}

由于 a * a 在32位平台上溢出,整数溢出触发未定义的行为,我有任何保证, hello world 实际上会出现在我的屏幕上?

Since a * a overflows on 32 bit platforms, and integer overflow triggers undefined behavior, do I have any guarantees at all that hello world will actually appear on my screen?

我根据以下标准语句从我的问题中删除了signed部分:

I removed the "signed" part from my question based on the following standard quotes:

(§5/ 5 C ++ 03,§5/ 4 C ++ 11)如果在表达式求值期间,结果不是数学定义的或不在可表示值的范围内

(§5/5 C++03, §5/4 C++11) If during the evaluation of an expression, the result is not mathematically defined or not in the range of representable values for its type, the behavior is undefined.

(§3.9.1/ 4)无符号整数,声明为 unsigned ,应遵守算术模2 ^ n的定律,其中n是整数的特定大小的值表示中的位数。这意味着无符号算术不会溢出,因为无法由生成的无符号整数类型表示的结果被减去模数,该数字大于可以由结果无符号整数表示的最大值类型。

(§3.9.1/4) Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2^n where n is the number of bits in the value representation of that particular size of integer. This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.


推荐答案

@Xeo在评论中指出在 C ++聊天中):

未定义的行为确实意味着

As pointed out by @Xeo in the comments (I actually brought it up in the C++ chat first):
Undefined behavior really means it and it can hit you when you least expect it.

最好的例子是: GCC失败?或未定义的行为?

在x86上,有符号整数溢出只是一个简单的换行。因此,通常情况下,您会希望在C或C ++中发生同样的情况。 但是,编译器可以介入 - 使用未定义的行为作为优化的机会。

On x86, signed integer overflow is just a simple wrap-around. So normally, you'd expect the same thing to happen in C or C++. However, the compiler can intervene - and use undefined behavior as an opportunity to optimize.

>

In the example taken from that question:

#include <iostream>
using namespace std;

int main(){
    int i = 0x10000000;

    int c = 0;
    do{
        c++;
        i += i;
        cout << i << endl;
    }while (i > 0);

    cout << c << endl;
    return 0;
}

当使用GCC编译时,GCC优化循环测试,

When compiled with GCC, GCC optimizes out the loop test and makes this an infinite loop.

这篇关于C ++中的整数溢出是多么的灾难性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆