bool addSigned(int a) { return a + 10 > a; }
bool addUnsigned(unsigned int a) { return a + 10 > a; }
int main() {
// UB reported only with -fsanitize=undefined:
bool res1 = addSigned (0x7ffffffe);
// UB reported only with -fsanitize=unsigned-integer-overflow:
bool res2 = addUnsigned(0xfffffffe);
}为什么?我希望res1在fsanitize=undefined/unsigned-integer-overflow下触发UB报告,而res2在这两种情况下都不会触发UB。我遗漏了什么?
发布于 2022-09-28 14:20:15
-fsanitize=undefined捕获res1,因为它会导致未定义的行为。它不会捕获res2,因为这不会导致未定义的行为。
根据https://source.android.com/docs/security/test/intsan的说法,-fsanitize=[[un]signed-]integer-overflow消毒液是为了启用特定的UBSan功能子集。UBSan确实包含默认禁用的模式,在该模式中,它会捕获无符号整数溢出。尽管这不是未定义的行为,但仍可能存在程序员希望避免发生无符号溢出的情况,此选项将帮助他们检测该溢出。
因此,-fsanitize=unsigned-integer-overflow只启用了这个陷阱。它将捕获所有无符号整数溢出的实例,如res2。它不会捕捉到其他任何东西,比如res1。
错误消息中的“未定义行为”具有误导性。UBSan可能以字符串“未定义的行为”作为其所有消息的前缀,甚至对于那些检测到实际上不是UB的东西的模糊模式也是如此。
https://stackoverflow.com/questions/73881732
复制相似问题