https://godbolt.org/z/qZVO3a
这是我看到的警告的最小复制品。显然UB可能不好,但我认为虽然下面的很多情况都没问题,但是有一些非常糟糕的用途……
在哪一点上未定义的行为有问题?
的 所有 强> UB是有问题的。
我的答案一般基于C,而不是基于gcc 4.7。
识别特定编译器版本的UB效果在解决问题方面具有一些优点。然而,人们永远不应该依赖UB效应来坚持下去。
UB缺少匹配参数。
custom_printf("HI THERE%d"); <source>:26:5: warning: format '%d' expects a matching 'int' argument [-Wformat]
没问题。额外的args是可以的,但可能是编码错误的步骤。
custom_printf("HI THERE", 1); <source>:27:5: warning: too many arguments for format [-Wformat-extra-args]
UB。 int 和 void * 可能有不同的规模,法律价值和功能传递机制,
int
void *
custom_printf("val: %d", (void*)0); <source>:28:5: warning: format '%d' expects argument of type 'int', but argument 2 has type 'void *' [-Wformat]
UB。与第28行相同
custom_printf("val: %p", 0); <source>:29:5: warning: format '%p' expects argument of type 'void *', but argument 2 has type 'int' [-Wformat]
UB。 int 和 long long 可能有不同的尺寸和功能传递机制,
long long
custom_printf("val: %lld", 1); <source>:30:5: warning: format '%lld' expects argument of type 'long long int', but argument 2 has type 'int' [-Wformat]
UB。类型可能在规模,法律价值和功能传递机制方面有所不同,
custom_printf("val: %s", (THING){"A", "AA", "CCCC"}); <source>:31:5: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'THING' [-Wformat]
UB:标准说明符无效 %0.30s 什么都可能发生。在为这个非标准说明符定义行为的选定系统上表现良好。
%0.30s
custom_printf("val: %0.30s","HI"); <source>:32:5: warning: '0' flag used with '%s' gnu_printf format [-Wformat]
UB喜欢第30行
custom_printf("val: %d",LLONG_MAX); <source>:33:5: warning: format '%d' expects argument of type 'int', but argument 2 has type 'long long int' [-Wformat]
调用代码时只有一个问题是使用返回值。然而 main() 特别在于代码就像a一样 return 0; 最后 - 如果该功能不以a结尾 return 。
main()
return 0;
return
<source>:34:1: warning: control reaches end of non-void function [-Wreturn-type]