# 整数溢出

**整数溢出**（integer overflow）是指对定宽整数进行算术运算时，产生的数学结果无法用结果类型表示的情况。当预期结果小于可表示的最小值时，这种情况称为**整数下溢**（integer underflow）；当硬件或语言按照规定的回绕规则替换为一个值时，这种行为称为**回绕**（wraparound），C11 等标准规定无符号类型的回绕是良定义的<sup>[1](https://cwe.mitre.org/data/definitions/190)</sup>。溢出之所以重要，是因为替换后的值是静默错误的，而在内存处理代码中，错误的大小、索引或偏移量可能演变为安全漏洞<sup>[2](https://www.usenix.org/system/files/usenixsecurity26-zhang-zheng.pdf)</sup>。

| 关键事实 | 详情 |
|---|---|
| 无符号范围 | n 位无符号整数表示 0 到 2<sup>n</sup> − 1；算术按模 2<sup>n</sup> 进行，因此在符合标准的 C 和 C++ 中，UINT_MAX + 1 必须求值为 0<sup>[3](https://users.cs.utah.edu/~regehr/papers/tosem15.pdf)</sup><sup> • </sup><sup>[4](https://en.cppreference.com/c/language/operator_arithmetic)</sup> |
| 有符号范围 | 二进制补码有符号整数的范围是 −2<sup>n−1</sup> 到 2<sup>n−1</sup> − 1，这是一个不对称的范围，其中 −2<sup>n−1</sup> 没有可表示的加法逆元<sup>[3](https://users.cs.utah.edu/~regehr/papers/tosem15.pdf)</sup> |
| 硬件行为 | 加法或减法溢出时，许多当代机器丢弃高位，存储加法器自然产生的低位；有些机器将这种情况记录在状态标志中<sup>[5](https://www.informit.com/articles/article.aspx?p=1959565&seqNum=13)</sup> |
| C/C++ 有符号溢出 | 未定义行为：运算可能回绕、陷入（例如在 GCC 的 `-ftrapv` 下），或允许优化器改变依赖溢出的代码<sup>[4](https://en.cppreference.com/c/language/operator_arithmetic)</sup> |
| Rust 语义 | 启用检查时，`+`、`-` 和 `*` 在溢出时触发恐慌；禁用检查时执行二进制补码回绕<sup>[6](https://rust-lang.github.io/rfcs/0560-integer-overflow.html)</sup> |
| Java 语义 | `+`、`-` 和 `*` 运算符静默回绕；Java 8 增加了精确的 `Math` 方法，要么返回正确值，要么抛出 `ArithmeticException`<sup>[7](https://open-std.org/jtc1/sc22/wg14/www/docs/n2543.pdf)</sup> |
| 安全权重 | 报告给 NVD 的整数溢出漏洞中，超过一半在 CVSSv2 量表上评分为 7–10（高危）<sup>[8](https://wurster.ca/glenn/publications/BlackBerry-Integer_Overflow-2016.pdf)</sup> |

## 可表示范围与极限

n 位无符号整数的范围是 0 到 2<sup>n</sup> − 1。所有现代平台上的有符号整数都使用二进制补码表示，其范围 −2<sup>n−1</sup> 到 2<sup>n−1</sup> − 1 是不对称的：最负的值没有对应的正值，因此对其取负会溢出<sup>[3](https://users.cs.utah.edu/~regehr/papers/tosem15.pdf)</sup>。

当 n 位无符号或二进制补码加法或减法溢出时，结果通过从真实数学结果中减去或加上 2<sup>n</sup> 来回绕<sup>[3](https://users.cs.utah.edu/~regehr/papers/tosem15.pdf)</sup>。在 C 中，无符号算术始终按模 2<sup>n</sup> 进行：对 `UINT_MAX` 加一得到 0，对 0 减一得到 `UINT_MAX`<sup>[4](https://en.cppreference.com/c/language/operator_arithmetic)</sup>。

**类型大小由实现定义。** 因此，溢出发生的临界点因平台而异；GCC 在 x86-64 上将 `0UL-1` 求值为 2<sup>64</sup> − 1，而在 x86 上求值为 2<sup>32</sup> − 1<sup>[3](https://users.cs.utah.edu/~regehr/papers/tosem15.pdf)</sup>。

## 硬件如何检测溢出

许多当代机器在加法或减法溢出时不会停止；它们丢弃结果的高位，存储加法器自然产生的低位<sup>[5](https://www.informit.com/articles/article.aspx?p=1959565&seqNum=13)</sup>。检测工作留给寄存器中的状态标志，例如 x86 的 EFLAGS 寄存器，它携带反映算术指令结果的进位标志和溢出标志<sup>[9](https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-vol-1-manual.pdf)</sup>。

这两个标志检测不同的情况。有符号溢出——越过字节有符号范围顶部的 7F–80 边界——由溢出标志检测；无符号溢出——越过 FF–00 边界——由进位标志检测<sup>[10](https://rosettacode.org/wiki/Integer_overflow)</sup>。对于有符号加法，有一条简单的规则：当且仅当操作数符号相同而和的符号相反时发生溢出，即使加法器有进位输入，该规则也成立<sup>[5](https://www.informit.com/articles/article.aspx?p=1959565&seqNum=13)</sup>。对于 32 位操作数的乘法，溢出意味着结果无法用 32 位表示，但无论有符号还是无符号，它总能以 64 位表示<sup>[5](https://www.informit.com/articles/article.aspx?p=1959565&seqNum=13)</sup>。

并非每台机器都提供这些状态位；MIPS 就没有，而且即使这些位存在，从高级语言访问它们也往往很困难甚至不可能，因此需要软件层面的检测<sup>[5](https://www.informit.com/articles/article.aspx?p=1959565&seqNum=13)</sup>。

有一份可信来源与上述图景相矛盾：SEI CERT 标准指出，在 x86-32 架构上有符号溢出会导致故障，可被利用为拒绝服务攻击<sup>[11](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int32-c/)</sup>，而《Hacker's Delight》参考书则指出，当代机器无一例外地存储回绕后的低位，而不是陷入<sup>[5](https://www.informit.com/articles/article.aspx?p=1959565&seqNum=13)</sup>。

## 语言语义

**C 和 C++：未定义行为。** 在 C 中，有符号整数算术溢出时，行为是未定义的：它可能按表示形式回绕（通常是二进制补码），在某些平台上或通过 `-ftrapv` 等编译器选项陷入，或允许优化器改变依赖溢出的代码<sup>[4](https://en.cppreference.com/c/language/operator_arithmetic)</sup>。C++ 委员会的一项调查指出了编译器实际实现的三种行为：模回绕（二进制补码，可通过 Clang 和 GCC 的 `-fwrapv` 获得）、陷入（通过 `-ftrapv`），以及“不可能发生”的优化器模型——大约从 2007 年起，一些优化器采用该模型，假设代码没有有符号溢出，并可能删除依赖溢出的代码<sup>[12](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1407r1.pdf)</sup>。在实践中，有符号溢出实际上是实现定义的，每个编译器都有一种明确理解的、可随标志改变的反应<sup>[12](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1407r1.pdf)</sup>。同一个符合标准的实现可以在不同上下文中产生不同的行为<sup>[11](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int32-c/)</sup>。这种未定义性是刻意的：它让编译器从 `i+1 > i` 这样的表达式中推断不变量，并将其替换为常量布尔值<sup>[13](https://nsl.cs.columbia.edu/projects/intflow/IntFlow.pdf)</sup>。C 自身内部有一个例外：对原子有符号整数类型的算术被定义为使用二进制补码并静默回绕，没有未定义结果<sup>[11](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int32-c/)</sup>。

**Java：保证回绕加精确方法。** Java 内置的整数运算符静默回绕结果，不指示溢出<sup>[14](https://wiki.sei.cmu.edu/confluence/display/java/NUM00-J.%2BDetect%2Bor%2Bprevent%2Binteger%2Boverflow)</sup>。Java 8（2014 年）在 `Math` 类中增加了精确计算方法，对于加法、减法、乘法、递增和递减，要么返回数学上正确的值，要么在溢出时抛出 `ArithmeticException`，而运算符保持不变<sup>[7](https://open-std.org/jtc1/sc22/wg14/www/docs/n2543.pdf)</sup>。

**Rust：恐慌或回绕，显式选择。** 在 Rust 中，算术溢出被定义为程序员错误，与有意为之的回绕算术不同；当 `debug_assert!` 断言启用时（例如在非优化构建中），实现必须插入在溢出时触发恐慌的动态检查<sup>[15](https://doc.rust-lang.org/stable/reference/behavior-not-considered-unsafe.html)</sup>。`+`、`-` 和 `*` 运算符在启用检查时溢出则触发恐慌，禁用时执行二进制补码回绕；以 `INT_MIN` 和 `-1` 为参数的除法和取余无条件触发恐慌；对于需要回绕语义的用例（如哈希函数），存在显式的回绕方法<sup>[6](https://rust-lang.github.io/rfcs/0560-integer-overflow.html)</sup>。Rust 为回绕与陷入行为提供了不同的整数类型，Swift 为陷入与回绕提供了不同的运算符，而 C++ 则通过 boost::safe_numerics 等类型化包装器来表达意图<sup>[2](https://www.usenix.org/system/files/usenixsecurity26-zhang-zheng.pdf)</sup>。

**C#、Haskell 与饱和模型。** C# 有受检查和不受检查的算术模式：运行时算术默认不受检查并回绕，而受检查的上下文抛出 `OverflowException`<sup>[10](https://rosettacode.org/wiki/Integer_overflow)</sup>。Haskell 在无界 `Integer` 之外提供固定大小的有符号 `Int`，`Data.Int` 和 `Data.Word` 中有带大小的类型；Haskell 2010 报告将固定精度类型的溢出结果留作未定义<sup>[10](https://rosettacode.org/wiki/Integer_overflow)</sup>。第三种模型是饱和，将值保持在其范围的顶部或底部，使得 MAX_INT + 1 等于 MAX_INT<sup>[16](https://lwn.net/Articles/1065889/)</sup>；Linux 内核将其用于 `refcount_t`<sup>[17](https://outflux.net/slides/2024/lss-na/)</sup>。

## 数据统计

一项对 C/C++ 项目中溢出相关缺陷的研究分类了 605 个案例：无符号溢出占 356 例（占无符号类别的 85%，占总数的 30%），有符号溢出占 74 例（占其类别的 17%，占总数的 6%），移位错误占 175 例（占 42%，占总数的 14%）<sup>[3](https://users.cs.utah.edu/~regehr/papers/tosem15.pdf)</sup>。该研究还发现并记录了包括 SQLite、PostgreSQL、SafeInt、GNU MPC、GMP、Firefox、LLVM、Python、BIND 和 OpenSSL 在内的软件中的未定义整数溢出行为，其中许多案例后来得到了修复。<sup>[3](https://users.cs.utah.edu/~regehr/papers/tosem15.pdf)</sup>

总体严重性很高：根据 NVD 统计，报告的整数溢出漏洞中超过一半在 CVSSv2 量表上评分为 7–10（高危）<sup>[8](https://wurster.ca/glenn/publications/BlackBerry-Integer_Overflow-2016.pdf)</sup>。经典的 Therac-25 放射治疗事故包含一个回绕缺陷：一个用非零值表示错误的 8 位变量回绕为零，绕过了关键的检查函数<sup>[3](https://users.cs.utah.edu/~regehr/papers/tosem15.pdf)</sup>。

## 安全影响

当溢出值被用于引用或分配内存时，它就变成了漏洞。一种典型模式是将溢出后的结果传给 `malloc()`，分配出比预期更小的缓冲区<sup>[8](https://wurster.ca/glenn/publications/BlackBerry-Integer_Overflow-2016.pdf)</sup>；用于索引或指针算术的溢出值会导致缓冲区溢出，最坏情况下导致攻击者执行任意代码<sup>[2](https://www.usenix.org/system/files/usenixsecurity26-zhang-zheng.pdf)</sup><sup> • </sup><sup>[11](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int32-c/)</sup>。有符号和无符号溢出都可能产生这些内存安全故障<sup>[2](https://www.usenix.org/system/files/usenixsecurity26-zhang-zheng.pdf)</sup>。

指针算术中的回绕带来更微妙的风险：当偏移量加到基地址上时，得到的指针可能最终位于该基地址之前，开发人员在编写处理缓冲区的例程时很容易忽略这一点。<sup>[16](https://lwn.net/Articles/1065889/)</sup>

已记录的案例包括 Mozilla 基金会安全公告 2007-01：Mozilla SVG 查看器中的堆缓冲区溢出，由有符号 `int` 值 `pen->num_vertices` 与 `size_t` 值 `sizeof(cairo_pen_vertex_t)` 相乘时的无符号整数回绕引起<sup>[18](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int30-c/)</sup>；CVE-2009-1385：对缓冲区长度进行未检查的减法，然后加上相应数量的字节<sup>[18](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int30-c/)</sup>；以及 CVE-2014-4377，与前者一并被引用为源于有符号溢出或无符号回绕<sup>[7](https://open-std.org/jtc1/sc22/wg14/www/docs/n2543.pdf)</sup>。

## 缓解措施与安全算术

**受检查算术内建函数。** GCC 提供了一系列受检查算术内建函数，包括 `__builtin_add_overflow`，它以无限精度中间计算执行加法，并报告是否溢出<sup>[19](https://snapshots.sourceware.org/gcc/docs/2026-10-04_20-23_1791145382/gcc/Integer-Overflow-Builtins.html)</sup>。

**更宽的类型。** 对于受检查的 n 位加法或减法，可以通过将结果存入 n+1 位变量来检查；对于受检查的 n 位乘法，结果应存入 2n 位变量<sup>[20](https://arxiv.org/pdf/1710.03720v9.pdf)</sup>。CERT 标准对 C 也有同样的观察：两个操作数的乘积总能使用较大操作数位数的两倍来表示，当 `long long` 的精度至少是 `int` 的两倍时，就能实现无溢出的乘法<sup>[11](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int32-c/)</sup>。对于 C/C++ 中的字符串到数值转换，`strtol`、`strtoul`、`strtoll` 和 `strtoull` 提供错误检测<sup>[21](https://research.cs.wisc.edu/mist/SoftwareSecurityCourse/Chapters/10-IntegerNumericErrors.pdf)</sup>。对于 Java，CERT 标准建议进行前置条件测试、使用更宽的类型或 `BigInteger`<sup>[14](https://wiki.sei.cmu.edu/confluence/display/java/NUM00-J.%2BDetect%2Bor%2Bprevent%2Binteger%2Boverflow)</sup>。

**饱和。** ARMv6 及之后的处理器提供饱和有符号加减法指令 `QADD` 和 `QSUB`，范围为 −2<sup>31</sup> 到 2<sup>31</sup> − 1；饱和算术可防御 CVE-2013-4511，同时允许内核继续运行，将可能被利用的漏洞转变为至多拒绝服务的状况<sup>[8](https://wurster.ca/glenn/publications/BlackBerry-Integer_Overflow-2016.pdf)</sup>。硬件饱和指令也存在于 SSE2（`PADDSW`）、PowerISA 和 ARM NEON 中<sup>[12](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1407r1.pdf)</sup>。

**编译器标志与运行时错误检测工具。** GCC 的 `-fwrapv` 为有符号和无符号整数定义模算术；`-ftrapv` 在有符号溢出时导致陷入，最可能是异常退出；不使用任一标志时，GCC 可能假设有符号整数永不溢出<sup>[11](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int32-c/)</sup>。Clang 的 UndefinedBehaviorSanitizer（UBSan）有符号整数溢出检查涵盖 `-ftrapv` 的所有检查加上有符号除法溢出（`INT_MIN/-1`），而且即使启用了 `-fwrapv`，仍会添加检查<sup>[22](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html)</sup>。UBSan 是当今用于检测 C/C++ 软件中整数溢出缺陷的主导工具，主要用于测试；其他在运行时陷入的编译器级防御包括 RICH、Archerr、IOC、blip、IntPatch 和 PaX 的溢出 GCC 插件<sup>[2](https://www.usenix.org/system/files/usenixsecurity26-zhang-zheng.pdf)</sup><sup> • </sup><sup>[23](https://www.usenix.org/system/files/conference/osdi12/osdi12-final-88.pdf)</sup>。Clang 还支持按类型设置 `overflow_behavior` 属性：`wrap` 将 `-fwrapv` 行为应用于单个类型，而 `trap` 即使全局启用了 `-fwrapv` 也强制对某个类型进行溢出检查，这对默认回绕的无符号整数特别有用<sup>[24](https://clang.llvm.org/docs/OverflowBehaviorTypes.html)</sup>。

## 近期进展

**Clang 中的按类型溢出行为。** `overflow_behavior` 类型属性让开发人员可以在一个程序中混合使用不同模型，独立于全局标志将特定类型标记为回绕或陷入<sup>[24](https://clang.llvm.org/docs/OverflowBehaviorTypes.html)</sup>。

**内核 API 讨论。** 2025 年的一篇 LWN 文章报道了内核对处理算术溢出的 API 的讨论，包括开发人员 Vincent Mailhol 提出的关于添加饱和整数的问题——这些整数保持在范围的顶部或底部而不是回绕<sup>[16](https://lwn.net/Articles/1065889/)</sup>。

**默认开启缓解措施的研究。** 编译器通常默认允许溢出静默发生，因为运行时检查带来高昂且不可预测的成本，这源于 ISA 的限制——溢出检测干扰常见优化并扩大指令流<sup>[2](https://www.usenix.org/system/files/usenixsecurity26-zhang-zheng.pdf)</sup>。在 USENIX Security 2026 上发表的研究考察了使整数溢出缓解措施默认开启的编译器和架构支持<sup>[2](https://www.usenix.org/system/files/usenixsecurity26-zhang-zheng.pdf)</sup>。

**2026 年 Rust 安全公告。** RUSTSEC-2026-0007 披露了流行的 `bytes` 软件包中 `BytesMut::reserve` 的整数溢出：在发布构建中，`new_cap + offset` 的未检查加法使 `usize` 溢出，可能将 `self.cap` 设置为高于实际分配的容量，随后 `spare_capacity_mut()` 等 API 信任被破坏的值，可能创建越界切片，导致未定义行为。该缺陷仅在溢出回绕的发布构建中可观察到；调试构建会触发恐慌<sup>[25](https://rustsec.org/advisories/RUSTSEC-2026-0007.html)</sup>。Android 在 Stagefright 之后，已经为某些媒体编解码器、解析器和蓝牙协议栈等高风险代码启用了 UBSan 溢出检查<sup>[2](https://www.usenix.org/system/files/usenixsecurity26-zhang-zheng.pdf)</sup>。

## References

1. [CWE-190: Integer Overflow or Wraparound, MITRE](https://cwe.mitre.org/data/definitions/190)
2. [An Integer Overflow Endgame: Compiler and Architecture Support for Default-On Integer Overflow Mitigation, USENIX Security 2026](https://www.usenix.org/system/files/usenixsecurity26-zhang-zheng.pdf)
3. [Understanding Integer Overflow in C/C++, ACM TOSEM (IOC study)](https://users.cs.utah.edu/~regehr/papers/tosem15.pdf)
4. [Arithmetic operators, cppreference.com](https://en.cppreference.com/c/language/operator_arithmetic)
5. [Overflow Detection, Hacker's Delight: The Basics, InformIT](https://www.informit.com/articles/article.aspx?p=1959565&seqNum=13)
6. [RFC 0560: Integer overflow, The Rust RFC Book](https://rust-lang.github.io/rfcs/0560-integer-overflow.html)
7. [Towards Integer Safety (N2543), ISO C committee](https://open-std.org/jtc1/sc22/wg14/www/docs/n2543.pdf)
8. [Towards Efficient Dynamic Integer Overflow Detection on ARM, BlackBerry 2016](https://wurster.ca/glenn/publications/BlackBerry-Integer_Overflow-2016.pdf)
9. [Intel 64 and IA-32 Architectures Software Developer's Manual, Volume 1](https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-vol-1-manual.pdf)
10. [Integer overflow, Rosetta Code](https://rosettacode.org/wiki/Integer_overflow)
11. [INT32-C. Ensure that operations on signed integers do not result in overflow, SEI CERT](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int32-c/)
12. [P1407R1: Signed Integer Overflow, C++ standards committee](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1407r1.pdf)
13. [IntFlow: Improving the Accuracy of Arithmetic Error Reporting, Columbia NSL](https://nsl.cs.columbia.edu/projects/intflow/IntFlow.pdf)
14. [NUM00-J. Detect or prevent integer overflow, SEI CERT Java standard](https://wiki.sei.cmu.edu/confluence/display/java/NUM00-J.%2BDetect%2Bor%2Bprevent%2Binteger%2Boverflow)
15. [Behavior not considered unsafe, The Rust Reference](https://doc.rust-lang.org/stable/reference/behavior-not-considered-unsafe.html)
16. [An API for handling arithmetic overflow, LWN.net](https://lwn.net/Articles/1065889/)
17. [Mitigating Integer Overflow in C, Linux Security Summit 2024](https://outflux.net/slides/2024/lss-na/)
18. [INT30-C. Ensure that unsigned integer operations do not wrap, SEI CERT](https://cmu-sei.github.io/secure-coding-standards/sei-cert-c-coding-standard/rules/integers-int/int30-c/)
19. [Integer Overflow Builtins, GCC documentation](https://snapshots.sourceware.org/gcc/docs/2026-10-04_20-23_1791145382/gcc/Integer-Overflow-Builtins.html)
20. [Practical Integer Overflow Prevention, arXiv](https://arxiv.org/pdf/1710.03720v9.pdf)
21. [Numeric Errors: Integers, UW-Madison software security course](https://research.cs.wisc.edu/mist/SoftwareSecurityCourse/Chapters/10-IntegerNumericErrors.pdf)
22. [UndefinedBehaviorSanitizer, Clang documentation](https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html)
23. [Improving Integer Security for Systems, USENIX OSDI 2012](https://www.usenix.org/system/files/conference/osdi12/osdi12-final-88.pdf)
24. [OverflowBehaviorTypes, Clang documentation](https://clang.llvm.org/docs/OverflowBehaviorTypes.html)
25. [RUSTSEC-2026-0007: bytes: Integer overflow in BytesMut::reserve](https://rustsec.org/advisories/RUSTSEC-2026-0007.html)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 物质世界与数学 › 数学与统计学 › 数与代数 › Arithmetic and number systems › Computational arithmetic › Integer overflow, underflow, and wraparound

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/integer-overflow

English original: https://www.edgepedia.org/integer-overflow
