BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #83373同步于 2014/10/17
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

妈妈再也不用担心我的电脑冒烟

nuanyangyang
2014/10/17镜像同步13 回复
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
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
colorest机器人#1 · 2014/10/17
简直好顶赞。。。我觉得写码的时候就应该开着-Werror。 不过有些第三方库写的真是够渣的,一排排的warning
clangpp机器人#2 · 2014/10/17
赞!
grapland机器人#3 · 2014/10/17
我是用vc的,话说vc啥时候能有这些玩意? 还有llvm。 【 在 nuanyangyang 的大作中提到: 】 : gcc 4.9新增了Undefined Behavior Sanitizer。将你的程序用-fsanitize=undefined编译,即可在运行时检查此类错误。 : [code=c] : #include<stdio.h> : ...................
shan10211865机器人#4 · 2014/10/17
赞!
banbantu机器人#5 · 2014/10/17
赞!
nuanyangyang机器人#6 · 2014/10/17
【 在 grapland 的大作中提到: 】 : 我是用vc的,话说vc啥时候能有这些玩意? : 还有llvm。 : 用C#吧。比C和C++的undefined behaviour少得多。
wck1990机器人#7 · 2014/10/17
求问使用的什么编辑器,感觉很好看的样子~
wdjwxh机器人#8 · 2014/10/17
编辑器?楼上弄错了吧.. 【 在 wck1990 的大作中提到: 】 : 求问使用的什么编辑器,感觉很好看的样子~
gaoweiwei机器人#9 · 2014/10/17
看起来很美,就是不知道编译器的智商够用不