返回信息流gcc 4.9新增了Undefined Behavior Sanitizer。将你的程序用-fsanitize=undefined编译,即可在运行时检查此类错误。
#include<stdio.h>
#include<stdint.h>
#include<inttypes.h>
int main(int argc, char *argv[]) {
int a, b;
printf("Input a and b for '+': ");
scanf("%d%d", &a, &b);
int c = a + b;
printf("%d + %d == %d\n", a, b, c);
printf("Input a and b for '<<': ");
scanf("%d%d", &a, &b);
int d = a << b;
printf("%d << %d == %d\n", a, b, d);
printf("Input a and b for '/': ");
scanf("%d%d", &a, &b);
int e = a / b;
printf("%d / %d == %d\n", a, b, e);
intptr_t ip;
printf("Input address to load: ");
scanf("%" PRIdPTR, &ip);
int *p = (int*)ip;
int f = *p;
printf("*(%" PRIdPTR " = %d\n", ip, f);
return 0;
}
有符号整数溢出是未定义行为,所以:
Input a and b for '+': 2147483647 1
undef.c:11:9: runtime error: signed integer overflow: 2147483647 + 1 cannot be represented in type 'int'
2147483647 + 1 == -2147483648
移位操作时,右操作数超过左操作数的长度,是未定义行为,所以:
Input a and b for '<<': 1 33
undef.c:18:15: runtime error: shift exponent 33 is too large for 32-bit type 'int'
1 << 33 == 2
除0错误是未定义行为,所以:
Input a and b for '/': 42 0
undef.c:25:15: runtime error: division by zero
[1] 1012 floating point exception ./undef
有符号整数除法的结果超过能表示的范围(对于int,唯一的例子是-2147483648/-1),也是未定义行为,所以:
Input a and b for '/': -2147483648 -1
undef.c:25:15: runtime error: division of -2147483648 by -1 cannot be represented in type 'int'
[1] 1046 floating point exception ./undef
NULL指针读写也是未定义行为,所以:
Input address to load: 0
undef.c:35:9: runtime error: load of null pointer of type 'int'
[1] 1052 segmentation fault ./undef
这是一条镜像帖。来源:北邮人论坛 / cpp / #83373同步于 2014/10/17
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
妈妈再也不用担心我的电脑冒烟
nuanyangyang
2014/10/17镜像同步13 回复
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
我是用vc的,话说vc啥时候能有这些玩意?
还有llvm。
【 在 nuanyangyang 的大作中提到: 】
: gcc 4.9新增了Undefined Behavior Sanitizer。将你的程序用-fsanitize=undefined编译,即可在运行时检查此类错误。
: [code=c]
: #include<stdio.h>
: ...................
【 在 grapland 的大作中提到: 】
: 我是用vc的,话说vc啥时候能有这些玩意?
: 还有llvm。
:
用C#吧。比C和C++的undefined behaviour少得多。