对每个INT X:X + 1>点¯x....这是总是正确的? [英] for every int x: x+1 > x .... is this always true?

查看:105
本文介绍了对每个INT X:X + 1>点¯x....这是总是正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习C在学校里,我试图让的基本概念保持。

我们的功课有问题,

对于每个 INT X:X + 1> X

确定是否真的还是假的,给推理,如果真和反如有虚假。

我很困惑,因为我们被教导说int类型是32位的,基本上,这意味着该整数是二进制格式。为X + 1加1的1十进制值?


解决方案

  X + 1> X

1 为除值 INT_MAX每个 INT 其中, INT_MAX + 1 是溢出,因此 X + 1> X 前pression是未定义行为X INT_MAX 的值。

这实际上意味着一个编译器优化了前pression正确的:

  X + 1> X

  1

由于 INT_MAX + 1 是未定义行为,编译器说,对于这个特定的权利> 前pression INT_MAX + 1 > INT_MAX

由于 X + 1> X 前pression是未定义行为点¯x== INT_MAX ,也无法假定 X + 1> X 可以是假的( 0 )。

请注意,如果 X 被声明为 unsigned int类型代替 INT 的情况是完全不同的。 unsigned int类型运算永远不会溢出(它们环绕): UINT_MAX + 1 == 0 ,因此 X + 1> X 0 X == UINT_MAX 和 1 所有其他 X 值。

现代编译器(如 GCC ),通常利用这个机会来优化它的前pression和 1

有关记录,有使用code像与已知的服务器程序的一些严重的安全问题:

 如果(PTR +偏移< PTR)

在code是为了触发安全条件,但编译器会优化了如果语句(用<$ C更换前pression $ C> 0 ),它允许攻击者获得对服务器程序的特权升级(通过打开一个可利用的缓冲区溢出的可能性,如果我没记错的话)。

I'm just starting to learn C at school, I'm trying to get a hold of the basic concepts.

Our homework has a question,

for every int x: x+1 > x

Determine whether true or false, give reasoning if true and counterexample if false.

I'm confused because we were taught that the type int is of 32-bits and basically that means the integer is in binary format. Is x+1 adding 1 to the decimal value of 1?

解决方案

x + 1 > x

is 1 for every int value except for value INT_MAX where INT_MAX + 1 is an overflow and therefore x + 1 > x expression is undefined behavior for x value of INT_MAX.

This actually means a compiler has the right to optimize out the expression:

x + 1 > x

by

1

As INT_MAX + 1 is undefined behavior, the compiler has the right to say that for this specific > expression INT_MAX + 1 is > INT_MAX.

As the x + 1 > x expression is undefined behavior for x == INT_MAX, it is also not safe to assume x + 1 > x can be false (0).

Note that if x was declared as an unsigned int instead of an int the situation is completely different. unsigned int operands never overflow (they wrap around): UINT_MAX + 1 == 0 and therefore x + 1 > x is 0 for x == UINT_MAX and 1 for all the other x values.

Modern compilers (like gcc) usually take the opportunity to optimize this expression and replace it with 1.

For the record, there was some serious security issues with known server programs using code like:

 if (ptr + offset < ptr)

The code was meant to trigger a safety condition but the compiler would optimize out the if statement (by replacing the expression with 0) and it allowed an attacker to gain privilege escalation in the server program (by opening the possibility of an exploitable buffer overflow if I remember correctly).

这篇关于对每个INT X:X + 1&GT;点¯x....这是总是正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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