命名空间
变体
操作

未定义行为

来自 cppreference.cn
< cpp‎ | language
 
 
C++ 语言
 
 

如果违反了语言的某些规则,则会使整个程序变得毫无意义。

目录

[编辑] 解释

C++ 标准精确地定义了可观察行为的每个 C++ 程序,该程序不属于以下类别之一

  • 病式 - 程序具有语法错误或可诊断的语义错误。
  • 即使符合标准的 C++ 编译器定义了将含义赋予此类代码的语言扩展(例如使用变长数组),也需要发出诊断信息。
  • 标准的文本使用 shallshall notill-formed 来指示这些要求。
  • 病式,无需诊断 - 程序具有语义错误,这些错误在一般情况下可能无法诊断(例如,违反 ODR 或其他仅在链接时可检测到的错误)。
  • 如果执行此类程序,则行为是未定义的。
  • 实现定义的行为 - 程序的行为在不同实现之间有所不同,并且符合标准的实现必须记录每种行为的效果。
  • 未指明的行为 - 程序的行为在不同实现之间有所不同,并且符合标准的实现不需要记录每种行为的效果。
  • 例如,求值顺序、相同的字符串字面量是否不同、数组分配开销的数量等等。
  • 每个未指明的行为都会产生一组有效结果之一。
  • 错误行为 - 建议实现诊断的(不正确的)行为。
  • 错误行为始终是不正确的程序代码的后果。
  • 常量表达式的求值永远不会导致错误行为。
  • 如果执行包含指定为具有错误行为的操作,则允许并建议实现发出诊断信息,并允许在操作后的未指定时间终止执行。
  • 如果实现可以确定在关于程序行为的特定于实现的假设集下可以达到错误行为,则实现可以发出诊断信息,这可能会导致误报。
错误行为的示例
#include <cassert>
#include <cstring>
 
void f()
{   
    int d1, d2;       // d1, d2 have erroneous values
    int e1 = d1;      // erroneous behavior
    int e2 = d1;      // erroneous behavior
    assert(e1 == e2); // holds
    assert(e1 == d1); // holds, erroneous behavior
    assert(e2 == d1); // holds, erroneous behavior
 
    std::memcpy(&d2, &d1, sizeof(int)); // no erroneous behavior, but
                                        // d2 has an erroneous value
 
    assert(e1 == d2); // holds, erroneous behavior
    assert(e2 == d2); // holds, erroneous behavior
}
 
unsigned char g(bool b)
{
    unsigned char c;     // c has erroneous value
    unsigned char d = c; // no erroneous behavior, but d has an erroneous value
    assert(c == d);      // holds, both integral promotions have erroneous behavior
    int e = d;           // erroneous behavior
    return b ? d : 0;    // erroneous behavior if b is true
}
(自 C++26 起)
  • 未定义行为 - 程序的行为没有任何限制。
  • 未定义行为的一些示例包括数据竞争、数组边界之外的内存访问、有符号整数溢出、空指针解引用、表达式中多次修改同一标量 没有任何中间序列点(直到 C++11)这是无序的(自 C++11 起)、通过不同类型的指针访问对象等。
  • 实现不需要诊断未定义行为(尽管许多简单情况都会被诊断出来),并且编译后的程序不需要执行任何有意义的操作。
  • 运行时未定义行为 - 行为是未定义的,除非它发生在作为核心常量表达式的表达式求值期间。
(自 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 上观察到的

#include <cstdio>
 
int main()
{
    bool p; // uninitialized local variable
    if (p)  // UB access to uninitialized scalar
        std::puts("p is true");
    if (!p) // UB access to uninitialized scalar
        std::puts("p is false");
}

可能的输出

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.

[编辑] 参考文献

扩展内容
  • C++23 标准 (ISO/IEC 14882:2024)
  • 3.25 病式程序 [defns.ill.formed]
  • 3.26 实现定义的行为 [defns.impl.defined]
  • 3.66 未指明的行为 [defns.unspecified]
  • 3.68 良式程序 [defns.well.formed]
  • C++20 标准 (ISO/IEC 14882:2020)
  • TBD 病式程序 [defns.ill.formed]
  • TBD 实现定义的行为 [defns.impl.defined]
  • TBD 未指明的行为 [defns.unspecified]
  • TBD 良式程序 [defns.well.formed]
  • C++17 标准 (ISO/IEC 14882:2017)
  • TBD 病式程序 [defns.ill.formed]
  • TBD 实现定义的行为 [defns.impl.defined]
  • TBD 未指明的行为 [defns.unspecified]
  • TBD 良式程序 [defns.well.formed]
  • C++14 标准 (ISO/IEC 14882:2014)
  • TBD 病式程序 [defns.ill.formed]
  • TBD 实现定义的行为 [defns.impl.defined]
  • TBD 未指明的行为 [defns.unspecified]
  • TBD 良式程序 [defns.well.formed]
  • C++11 标准 (ISO/IEC 14882:2011)
  • TBD 病式程序 [defns.ill.formed]
  • TBD 实现定义的行为 [defns.impl.defined]
  • TBD 未指明的行为 [defns.unspecified]
  • TBD 良式程序 [defns.well.formed]
  • C++98 标准 (ISO/IEC 14882:1998)
  • TBD 病式程序 [defns.ill.formed]
  • TBD 实现定义的行为 [defns.impl.defined]
  • TBD 未指明的行为 [defns.unspecified]
  • TBD 良式程序 [defns.well.formed]

[编辑] 参见

[[assume(表达式)]]
(C++23)
指定表达式在给定点始终求值为 true
(属性说明符)[编辑]
(C++26)
指定如果对象未初始化,则它具有不确定值
(属性说明符)[编辑]
标记不可达的执行点
(函数) [编辑]
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++ 程序员的未定义行为指南