相关疑难解决方法(0)

为什么/如何在此签名溢出测试中编译未定义的行为,以便它可以在x86上工作但不能在ARM64上工作?

当我在断言测试运行期间遇到一个奇怪的问题时,我正在自学CSAPP并得到一个奇怪的结果.

我不知道该怎么开始这个问题,所以让我先得到代码(文件名在评论中可见):

// File: 2.30.c
// Author: iBug

int tadd_ok(int x, int y) {
    if ((x ^ y) >> 31)
        return 1;  // A positive number and a negative integer always add without problem
    if (x < 0)
        return (x + y) < y;
    if (x > 0)
        return (x + y) > y;
    // x == 0
    return 1;
}
Run Code Online (Sandbox Code Playgroud)
// File: 2.30-test.c
// Author: iBug

#include <assert.h>

int tadd_ok(int x, int y);

int main() {
    assert(sizeof(int) == 4); …
Run Code Online (Sandbox Code Playgroud)

c gcc integer-overflow undefined-behavior arm64

3
推荐指数
2
解决办法
353
查看次数

编译器是否有可能检测到整数溢出或其他数据类型溢出的可能性?

是否可以在编译时检测或防止整数溢出而不是在运行时?

如果未检测到溢出并且在运行时发生溢出,是否可以检测到?我在某处读到,如果某个操作出现溢出,处理器将设置一个特定的标志.

如何读取处理器的特定标志?我应该问这是一个单独的问题吗?

编辑:

我的问题是签名和无符号溢出.当我们有一个无符号变量时,它仍然会溢出并将自身设置为0或接近0的东西,对吧?还是我缺少的东西?

c c++ error-handling warnings integer-overflow

2
推荐指数
1
解决办法
361
查看次数

当 x=0x80000000,y = 1(32 位补码)时,为什么 `x - y &lt;= x` 为真?

我想知道是否x - y溢出。

下面是我的代码。

#include <stdio.h>

/* Determine whether arguments can be subtracted without overflow */
int tsub_ok(int x, int y)
{
    return (y <= 0 && x - y >= x) || (y >= 0 && x - y <= x);
}

int main()
{
    printf("0x80000000 - 1 : %d\n", tsub_ok(0x80000000, 1));
}
Run Code Online (Sandbox Code Playgroud)

为什么我不能得到我期望的结果?

c

0
推荐指数
1
解决办法
104
查看次数

如何捕获C++中的数据类型溢出异常?

这里,base可能会溢出超出int的限制,导致运行时错误,此时我打算捕获引发的运行时错误并处理它,所以我尝试了try-catch块,但它没有被捕获。

int base=1;
try
{
     base *= 10;
     //some code
}
catch(...)
{
     //some code
}
Run Code Online (Sandbox Code Playgroud)

c++ try-catch

0
推荐指数
1
解决办法
67
查看次数