未定义行为
来自 cppreference.cn
如果违反了语言的某些规则,则会使整个程序变得毫无意义。
目录 |
[编辑] 解释
C++ 标准精确地定义了可观察行为的每个 C++ 程序,该程序不属于以下类别之一
- 病式 - 程序具有语法错误或可诊断的语义错误。
- 即使符合标准的 C++ 编译器定义了将含义赋予此类代码的语言扩展(例如使用变长数组),也需要发出诊断信息。
- 标准的文本使用 shall、shall not 和 ill-formed 来指示这些要求。
- 如果执行此类程序,则行为是未定义的。
- 实现定义的行为 - 程序的行为在不同实现之间有所不同,并且符合标准的实现必须记录每种行为的效果。
- 例如,std::size_t 的类型或字节中的位数,或 std::bad_alloc::what 的文本。
- 实现定义的行为的一个子集是特定于区域设置的行为,这取决于实现提供的 区域设置。
- 未指明的行为 - 程序的行为在不同实现之间有所不同,并且符合标准的实现不需要记录每种行为的效果。
|
(自 C++26 起) |
- 未定义行为 - 程序的行为没有任何限制。
|
(自 C++11 起) |
[编辑] UB 与优化
由于正确的 C++ 程序没有未定义行为,因此当实际具有 UB 的程序在启用优化的情况下编译时,编译器可能会产生意外的结果
例如,
[编辑] 有符号溢出
int foo(int x) { return x + 1 > x; // either true or UB due to signed overflow }
可能会编译为(演示)
foo(int): mov eax, 1 ret
[编辑] 越界访问
int table[4] = {}; bool exists_in_table(int v) { // return true in one of the first 4 iterations or UB due to out-of-bounds access for (int i = 0; i <= 4; i++) if (table[i] == v) return true; return false; }
可能会编译为(演示)
exists_in_table(int): mov eax, 1 ret
[编辑] 未初始化的标量
std::size_t f(int x) { std::size_t a; if (x) // either x nonzero or UB a = 42; return a; }
可能会编译为(演示)
f(int): mov eax, 42 ret
显示的输出是在旧版本的 gcc 上观察到的
运行此代码
可能的输出
p is true p is false
[编辑] 无效的标量
int f() { bool b = true; unsigned char* p = reinterpret_cast<unsigned char*>(&b); *p = 10; // reading from b is now UB return b == 0; }
可能会编译为(演示)
f(): mov eax, 11 ret
[编辑] 空指针解引用
这些示例演示了从空指针解引用结果中读取。
int foo(int* p) { int x = *p; if (!p) return x; // Either UB above or this branch is never taken else return 0; } int bar() { int* p = nullptr; return *p; // Unconditional UB }
可能会编译为(演示)
foo(int*): xor eax, eax ret bar(): ret
[编辑] 访问传递给 std::realloc 的指针
选择 clang 以观察显示的输出
运行此代码
#include <cstdlib> #include <iostream> int main() { int* p = (int*)std::malloc(sizeof(int)); int* q = (int*)std::realloc(p, sizeof(int)); *p = 1; // UB access to a pointer that was passed to realloc *q = 2; if (p == q) // UB access to a pointer that was passed to realloc std::cout << *p << *q << '\n'; }
可能的输出
12
[编辑] 没有副作用的无限循环
选择 clang 或最新的 gcc 以观察显示的输出。
运行此代码
#include <iostream> bool fermat() { const int max_value = 1000; // Non-trivial infinite loop with no side effects is UB for (int a = 1, b = 1, c = 1; true; ) { if (((a * a * a) == ((b * b * b) + (c * c * c)))) return true; // disproved :() a++; if (a > max_value) { a = 1; b++; } if (b > max_value) { b = 1; c++; } if (c > max_value) c = 1; } return false; // not disproved } int main() { std::cout << "Fermat's Last Theorem "; fermat() ? std::cout << "has been disproved!\n" : std::cout << "has not been disproved.\n"; }
可能的输出
Fermat's Last Theorem has been disproved!
[编辑] 带有诊断消息的病式
请注意,编译器被允许以某种方式扩展语言,从而为病式程序赋予意义。C++ 标准在这种情况下唯一的要求是诊断消息(编译器警告),除非程序是“无需诊断的病式”。
例如,除非通过 --pedantic-errors
禁用语言扩展,否则 GCC 将编译以下示例仅发出警告,即使它在 C++ 标准中作为“错误”的示例出现(另请参见GCC Bugzilla #55783)
运行此代码
#include <iostream> // Example tweak, do not use constant double a{1.0}; // C++23 standard, §9.4.5 List-initialization [dcl.init.list], Example #6: struct S { // no initializer-list constructors S(int, double, double); // #1 S(); // #2 // ... }; S s1 = {1, 2, 3.0}; // OK, invoke #1 S s2{a, 2, 3}; // error: narrowing S s3{}; // OK, invoke #2 // — end example] S::S(int, double, double) {} S::S() {} int main() { std::cout << "All checks have passed.\n"; }
可能的输出
main.cpp:17:6: error: type 'double' cannot be narrowed to 'int' in initializer ⮠ list [-Wc++11-narrowing] S s2{a, 2, 3}; // error: narrowing ^ main.cpp:17:6: note: insert an explicit cast to silence this issue S s2{a, 2, 3}; // error: narrowing ^ static_cast<int>( ) 1 error generated.
[编辑] 参考文献
扩展内容 |
---|
|
[编辑] 参见
[[assume(表达式)]] (C++23) |
指定表达式在给定点始终求值为 true (属性说明符) |
[[indeterminate]] (C++26) |
指定如果对象未初始化,则它具有不确定值 (属性说明符) |
(C++23) |
标记不可达的执行点 (函数) |
C 文档 用于 未定义行为
|
[编辑] 外部链接
1. | LLVM 项目博客:每个 C 程序员都应该了解的未定义行为 #1/3 |
2. | LLVM 项目博客:每个 C 程序员都应该了解的未定义行为 #2/3 |
3. | LLVM 项目博客:每个 C 程序员都应该了解的未定义行为 #3/3 |
4. | 未定义行为可能导致时间旅行(以及其他事情,但时间旅行是最有趣的) |
5. | 理解 C/C++ 中的整数溢出 |
6. | NULL 指针的乐趣,第 1 部分(Linux 2.6.30 中的本地漏洞,由空指针解引用导致的 UB 引起) |
7. | 未定义行为和费马最后定理 |
8. | C++ 程序员的未定义行为指南 |