Integer overflow: Difference between revisions

Content deleted Content added
Bender the Bot (talk | contribs)
 
(415 intermediate revisions by more than 100 users not shown)
Line 1:
{{Short description|Computer arithmetic error}}
{{Merge|Arithmetic overflow|date=December 2006}}
{{Use American English|date=January 2019}}
 
[[File:Odometer rollover.jpg|thumb|upright=1.3|Integer overflow can be demonstrated through an [[odometer]] overflowing, a mechanical version of the phenomenon. All digits are set to the maximum 9 and the next increment of the white digit causes a cascade of carry-over additions setting all digits to 0, but there is no higher digit (1,000,000s digit) to change to a 1, so the counter resets to zero. This is ''wrapping'' in contrast to ''saturating''.]]
In [[computer programming]], an '''integer overflow''' occurs when an [[arithmetic]] operation attempts to create a numeric value that is larger than can be represented within the available storage space. For instance, adding 1 to the largest value that can be represented constitutes an integer overflow. The most common result in these cases is for the least significant representable bits of the result to be stored (the result is said to ''wrap''). On some [[processor]]s the result [[saturation arithmetic|saturates]], that is once the maximum value is reached attempts to make it larger simply return the maximum result.
 
In [[computer programming]], an '''integer overflow''' occurs when an [[arithmetic]] operation on integers attempts to create a numeric value that is outside of the range that can be represented with a given number of digits – either higher than the maximum or lower than the minimum representable value.
==Origin==
The [[register width]] of a [[processor]] determines the range of values that can be represented. Typical [[Binary numeral system|binary]] register widths include:
 
Integer overflow specifies an overflow of the [[data type]] [[Integer (computer science)|integer]]. An overflow (of any type) occurs when a [[computer program]] or system tries to store more data in a fixed-size ___location than it can handle, resulting in [[data loss]] or [[Data corruption|corruption]].<ref>{{cite web|url=https://www.lenovo.com/us/en/glossary/overflow-error |title=What is an overflow error?}}</ref> The most common implementation of integers in modern computers are [[two's complement]].<ref>E.g. "Signed integers are two's complement binary values that can be used to represent both positive and negative integer values", Section 4.2.1 in ''Intel 64 and IA-32 Architectures Software Developer's Manual'', Volume 1: Basic Architecture, November 2006</ref> In two's complement the [[Bit numbering#Most_significant_bit|most significant bit]] represents the [[Sign bit|sign]] (positive or negative), and the remaining [[Bit numbering#Signed_integer_example|least significant bits]] represent the number. Unfortunately, for most [[Computer architecture|architectures]] the [[Arithmetic logic unit|ALU]] doesn't know the [[Binary number|binary representation]] is [[Signedness|signed]]. [[Two's_complement#Arithmetic_operations|Arithmetic operations]] can result in a value of bits exceeding the fixed-size of bits representing the number, this causes the sign bit to be changed, an integer overflow. The most infamous examples are: [[2,147,483,647#In_computing|2,147,483,647]] + 1 = -2,147,483,648 and [[32-bit computing#Range_for_storing_integers|-2,147,483,648]] - 1 = 2,147,483,647.
: 8 bits (maximum representable value 255),
: 16 bits (maximum representable value 65,535),
: 32 bits (the most common width for personal computers [[as of 2005]], maximum representable value 4,294,967,295),
: 64 bits (maximum representable value 18,446,744,073,709,551,615),
: 128 bits (maximum representable value approx. 10<sup>38</sup>)
 
On some processors like [[graphics processing unit]]s (GPUs) and [[digital signal processor]]s (DSPs) which support [[saturation arithmetic]], overflowed results would be ''clamped'', i.e. set to the minimum value in the representable range if the result is below the minimum and set to the maximum value in the representable range if the result is above the maximum, rather than wrapped around.
Since an arithmetic operation may produce a result larger than the maximum representable value, a potential error condition may result. In the [[C (programming language)|C programming language]], for example, signed integer overflow causes [[undefined behavior]], although arithmetic on unsigned integers, however, is reduced [[modular arithmetic|modulo a power of two]], meaning that unsigned integers "wrap around" on overflow.
 
An overflow condition may give results leading to unintended behavior. In particular, if the possibility has not been anticipated, overflow can compromise a program's reliability and [[software security|security]].
<!-- Diagram that illustrates wrapping behavior of integer representation. -->
 
For some applications, such as timers and clocks, wrapping on overflow can be desirable. The [[C11 (C standard revision)|C11 standard]] states that for unsigned integers, modulo wrapping is the defined behavior and the term overflow never applies: "a computation involving unsigned operands can never overflow."<ref name="auto">{{cite web |url=https://webstore.ansi.org/RecordDetail.aspx?sku=ISO/IEC+9899:2011 |title=ISO/IEC 9899:2011 Information technology - Programming languages - C |author=ISO staff |website=ANSI.org}}</ref>
In [[computer graphics]] or [[signal processing]], it is typical to work on data that ranges from 0 to 1 or from -1 to 1. An example of this is a [[grayscale]] image where 0 represents black, 1 represents white, and values in-between represent varying shades of gray. One operation that you may want to support is brightening the image by multiplying every pixel by a constant. [[Saturated arithmetic]] allows you to just blindly multiply every [[pixel]] by that constant without worrying about overflow by just sticking to a reasonable outcome that all these pixels larger than 1 (i.e. [[high dynamic range imaging|"brighter than white"]]) just become white and all values "darker than black" just become black.
 
== Origin ==
==Security ramifications==
Integer overflow occurs when an [[arithmetic]] operation on integers attempts to create a numeric value that is outside of the range that can be represented with a given number of digits. In the context of computer programming, the integers are [[Binary numeral system|binary]], but any [[Positional notation|positional]] [[numeral system]] can have an invalid result of an arithmetic operation if positions are confined. As shown in the odometer example, using the [[decimal]] system, with the constraint of 6 positions ([[Numerical digit|digits]]) the following operation will have an invalid result: {{math|999999 + 1}}. Likewise, a binary system limited to 4 positions ([[bit|bits]]) will have an invalid result for the following operation: {{code|1111 + 1}}. For both examples the results will have a value exceeding the range that can be represented by the constraints. Another way to look at this problem is that the [[Significant figures|most significant]] position's operation has a [[Carry (arithmetic)|carry]] requiring another position/digit/bit to be allocated, breaking the constraints.
In some situations a program may make the assumption that a variable always contains a positive value. If the variable has a signed integer type an overflow can causes its value wrap and become negative, violating the assumption contained in the program and perhaps leading to unintended behavior. Similarly, subtracting from a small unsigned value may cause it to wrap to a large positive value which may also be an unexpected behavior.
 
All integers in computer programming have constraints of a max value and min value. The primary factors for determining the range is the allocation of bits and if it is [[Signedness|signed or unsigned]]. The [[Integer (computer science)#Standard_integer|standard integer]] depends on the [[Computing platform|platform]] and [[programming language]]. Additional integer representation can be less than or greater than standard. Examples are the [[Integer (computer science)#Short_integer|short integer]] and [[Integer (computer science)#Long_integer|long integer]] respectively. Even [[Arbitrary-precision arithmetic|arbitrary-precision]] exists, but would be limited by [[Arbitrary-precision arithmetic#Pre-set_precision|pre-set precision]] or available system memory.
Some languages, such as [[Lisp (programming language)|Lisp]] and [[Ada (programming language)|Ada]], provide mechanisms that, if used, result in accidental overflow throwing an exception. Many languages do not support such functionality.
 
Most [[Arithmetic logic unit|ALUs]] perform operations on [[Signedness|unsigned]] (positive) [[Binary number|binary numbers]]. These ALUs do not have any capability of dealing with [[Signedness|signed]] (positive and negative) numbers. Because most numbers in programs need to support negative numbers, an abstraction is used, redefining the bits' meaning to include a sign. The most common solution is [[two's complement]]. Most programming languages provide this construct. A signed 32-bit integer will use the [[Bit numbering#Most_significant_bit|most significant bit]] to signify the [[Sign bit|sign]] (positive or negative), and the remaining [[Bit numbering#Signed_integer_example|31-bits]] to represent the number. When an [[Two's_complement#Arithmetic_operations|operation]] occurs that results in a [[Carry (arithmetic)|carry]] past the 31-bits allocated for the number, the sign bit is overwritten. The ALU doesn't know it did anything wrong. It is up to the program to detect this overflow fault.
==Techniques for mitigating integer overflow problems==
 
For usage of unsigned integers of [[register width]], the ALU is not capable of returning a result with more bits outside its width. The ALU will return the result along with a flag for carry-out. When these flags are returned true, the ALU has detected overflow.
List of techniques and methods that might be used to mitigate against the consequences of integer overflow:
 
After overflow is detected, it is up to the program to handle this with additional logic. The resulting value from the operation is [[Data corruption|corrupted]] and can cause additional issues if not handled properly.
* The effects of integer-based attacks for C/C++ and how to defend against them by using subtyping in [http://www.cs.cmu.edu/~dbrumley/pubs/integer-ndss-07.pdf Efficient and Accurate Detection of Integer-based Attacks].
 
Using integers of the same size as the [[Arithmetic logic unit|ALU]]'s [[register width]] will have the best performance in most applications. [[Single instruction, multiple data|SIMD]] [[Instruction set architecture|instruction]] extensions can provide single operations for integers exceeding the register width. For [[x86]] [[32-bit computing|32-bit processors]] the [[Streaming SIMD extensions]] (SSE2) added registers for 64-bit integers. For [[x86-64]] [[64-bit computing|64-bit processors]] the [[Advanced Vector Extensions]] (AVX) added registers up to 512-bit integers.<ref>{{cite web|url=https://www.intel.com/content/www/us/en/content-details/812656/intel-avx-512-fast-modular-multiplication-technique-technology-guide.html|title=Intel® AVX-512 - Fast Modular Multiplication Technique}}</ref>
 
{{Table alignment}}
{| class="wikitable defaultright"
|+ Typical Integer Boundaries
|-
! Bits !! Alias{{efn|name=alias}} !! Range !! Signed Range{{efn|name=signed}} !! Unsigned Range
|-
! rowspan="2" style="white-space: preserve nowrap; text-align:center;" | [[8-bit computing|8-bit]]
| rowspan="2" style="text-align:center;" | [[byte]]<ref name="byte">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.byte|title=.NET Byte Struct }}</ref>{{efn|name=byte}}, sbyte,<ref name="sbyte">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.sbyte|title=.NET SByte Struct }}</ref> [[octet (computing)|octet]]
| rowspan="2" style="white-space: preserve nowrap; text-align:center;" | 2<sup>8</sup> − 1 || {{small|-128<ref name="sbyte.min">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.minvalue |title=.NET SByte.MinValue Field }}</ref>}} || {{small|0<ref name="byte.min">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.byte.minvalue |title=.NET Byte.MinValue Field }}</ref>}}
|-
|-
| {{small|127<ref name="sbyte.max">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.sbyte.maxvalue |title=.NET SByte.MaxValue Field }}</ref>}} || {{small|[[255 (number)#In_computing|255]]<ref name="byte.max">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.byte.maxvalue |title=.NET Byte.MaxValue Field }}</ref>}}
|-
|-
! rowspan="2" style="white-space: preserve nowrap; text-align:center;" | [[16-bit computing|16-bit]]
| rowspan="2" style="text-align:center;" | [[Word (data type)|word]], [[Integer (computer science)#Short_integer|short]], int16,<ref name="int16">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int16|title=.NET Int16 Struct }}</ref> uint16<ref name="uint16">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint16|title=.NET UInt16 Struct }}</ref>
| rowspan="2" style="white-space: preserve nowrap; text-align:center;" | 2<sup>16</sup> − 1 || {{small|−32,768<ref name="int16.min">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int16.minvalue |title=.NET Int16.MinValue Field }}</ref>}} || {{small|0<ref name="uint16.min">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint16.minvalue |title=.NET UInt16.MinValue Field }}</ref>}}
|-
|-
| {{small|32,767<ref name="int16.max">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int16.maxvalue |title=.NET Int16.MaxValue Field }}</ref>}} || {{small|[[65,535#In_computing|65,535]]<ref name="uint16.max">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint16.maxvalue |title=.NET UInt16.MaxValue Field }}</ref>}}
|-
|-
! rowspan="2" style="white-space: preserve nowrap; text-align:center;" | [[32-bit computing|32-bit]]{{efn|name=common2005}}
| rowspan="2" style="white-space: preserve nowrap; text-align:center;" | int32,<ref name="int32">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int32|title=.NET Int32 Struct }}</ref> uint32<ref name="uint32">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint32|title=.NET UInt32 Struct }}</ref>
| rowspan="2" style="white-space: preserve nowrap; text-align:center;" | 2<sup>32</sup> − 1 || {{small|[[32-bit computing#Range_for_storing_integers|-2,147,483,648]]<ref name="int32.min">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int32.minvalue |title=.NET Int32.MinValue Field }}</ref>}} || {{small|0<ref name="uint32.min">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint32.minvalue |title=.NET UInt32.MinValue Field }}</ref>}}
|-
|-
| {{small|[[2,147,483,647]]<ref name="int32.max">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int32.maxvalue |title=.NET Int32.MaxValue Field }}</ref>}} || {{small|[[4,294,967,295#In_computing|4,294,967,295]]<ref name="uint32.max">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint32.maxvalue |title=.NET UInt32.MaxValue Field }}</ref>}}
|-
|-
! rowspan="2" style="white-space: preserve nowrap; text-align:center;" | [[64-bit computing|64-bit]]{{efn|name=common2025}}
| rowspan="2" style="white-space: preserve nowrap; text-align:center;" | int64,<ref name="int64">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int64|title=.NET Int64 Struct }}</ref> uint64<ref name="uint64">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint64|title=.NET UInt64 Struct }}</ref>
| rowspan="2" style="white-space: preserve nowrap; text-align:center;" | 2<sup>64</sup> − 1 || {{small|−9,223,372,036,854,775,808<ref name="int64.min">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int64.minvalue |title=.NET Int64.MinValue Field }}</ref>}} || {{small|0<ref name="uint64.min">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint64.minvalue |title=.NET UInt64.MinValue Field }}</ref>}}
|-
|-
| {{small|[[Power of two#2^63-1|9,223,372,036,854,775,807]]<ref name="int64.max">
{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int64.maxvalue |title=.NET Int64.MaxValue Field }}
</ref>}} || {{small|[[Power of two#2^64-1|18,446,744,073,709,551,615]]<ref name="uint64.max">
{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint64.maxvalue |title=.NET UInt64.MaxValue Field }}
</ref>}}
|-
|-
! rowspan="2" style="white-space: preserve nowrap; text-align:center;" | [[128-bit computing|128-bit]]
| rowspan="2" style="white-space: preserve nowrap; text-align:center;" | int128,<ref name="int128">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.int128|title=.NET Int128 Struct }}</ref> uint128<ref name="uint128">{{cite web |url=https://learn.microsoft.com/en-us/dotnet/api/system.uint128 |title=.NET UInt128 Struct }}</ref>
| rowspan="2" style="white-space: preserve nowrap; text-align:center;" | 2<sup>128</sup> − 1 || {{small|−170,141,183,460,469,231,731,687,303,715,884,105,728}} || {{small|0}}
|-
|-
| {{small|170,141,183,460,469,231,731,687,303,715,884,105,727}} || {{small|340,282,366,920,938,463,463,374,607,431,768,211,455}}
|-
|}
 
{{notelist|refs=
{{efn|name=alias|The integer (int) data type typically uses [[two's complement]] thus are signed. The 'u' prefix designates the unsigned implementation.}}
{{efn|name=signed|Signed Ranges are assuming [[two's complement]]}}
{{efn|name=byte|The byte data type is typically unsigned by default. The 's' prefix designates the signed implementation.}}
{{efn|name=common2005|The most common for personal computers {{as of|2005|lc=on}}.}}
{{efn|name=common2025|The most common for personal computers {{as of|2025|lc=on}}.}}
}}
 
 
When an unsigned arithmetic operation produces a result larger than the maximum above for an N-bit integer, an overflow reduces the result to [[Modulo operation|modulo]] N-th power of 2, retaining only the least significant bits of the result and effectively causing a ''wrap around''.
 
In particular, multiplying or adding two integers may result in a value that is unexpectedly small, and subtracting from a small integer may cause a wrap to a large positive value (for example, 8-bit integer addition 255 + 2 results in 1, which is {{math|257 mod 2<sup>8</sup>}}, and similarly subtraction 0 − 1 results in 255, a [[two's complement]] representation of −1).
 
{{anchor|Security ramifications}}
Such wrap around may cause security detriments&mdash;if an overflowed value is used as the number of bytes to allocate for a buffer, the buffer will be allocated unexpectedly small, potentially leading to a [[buffer overflow]] which, depending on the use of the buffer, might in turn cause arbitrary code execution.
 
If the variable has a [[Signed number representations|signed integer]] type, a program may make the assumption that a variable always contains a positive value. An integer overflow can cause the value to wrap and become negative, which violates the program's assumption and may lead to unexpected behavior (for example, 8-bit integer addition of 127 + 1 results in −128, a two's complement of 128). (A solution for this particular problem is to use unsigned integer types for values that a program expects and assumes will never be negative.)
 
==Flags==
Most computers have two dedicated processor flags to check for overflow conditions.
 
The [[carry flag]] is set when the result of an addition or subtraction, considering the operands and result as unsigned numbers, does not fit in the given number of bits. This indicates an overflow with a [[carry (arithmetic)|''carry'' or ''borrow'']] from the [[most significant bit]]. An immediately following ''add with carry'' or ''subtract with borrow'' operation would use the contents of this flag to modify a register or a memory ___location that contains the higher part of a multi-word value.
 
The [[overflow flag]] is set when the result of an operation on signed numbers does not have the sign that one would predict from the signs of the operands, e.g., a negative result when adding two positive numbers. This indicates that an overflow has occurred and the signed result represented in [[two's complement]] form would not fit in the given number of bits.
 
==Definition variations and ambiguity==
For an unsigned type, when the ideal result of an operation is outside the type's representable range and the returned result is obtained by wrapping, then this event is commonly defined as an overflow. In contrast, the C11 standard defines that this event is not an overflow and states "a computation involving unsigned operands can never overflow."<ref name="auto"/>
 
When the ideal result of an integer operation is outside the type's representable range and the returned result is obtained by clamping, then this event is commonly defined as a saturation. Use varies as to whether a saturation is or is not an overflow. To eliminate ambiguity, the terms wrapping overflow<ref>{{cite web |url=https://www.mathworks.com/help/simulink/gui/wrap-on-overflow.html?searchHighlight=overflow&s_tid=doc_srchtitle |title=Wrap on overflow - MATLAB & Simulink |website=www.mathworks.com}}</ref> and saturating overflow<ref>{{cite web |url=https://www.mathworks.com/help/simulink/gui/saturate-on-overflow.html?searchHighlight=overflow&s_tid=doc_srchtitle |title=Saturate on overflow - MATLAB & Simulink |website=www.mathworks.com}}</ref> can be used.
 
Integer Underflow is an improper term used to signify the negative side of overflow. This terminology confuses the prefix "over" in overflow to be related to the [[Sign (mathematics)|sign]] of the number. Overflowing is related the boundary of bits, specifically the number's bits overflowing. In [[two's complement]] this overflows into the sign bit. Many references can be found to integer underflow, but lack merit. For example: CWE-191 provides two code examples that are classic overflow and cast exceptions. CWE-191 then circularly references ''24 Deadly Sins of Software Security''.<ref>{{cite web |url=https://cwe.mitre.org/data/definitions/191.html |title=CWE - CWE-191: Integer Underflow (Wrap or Wraparound) (3.1) |website=cwe.mitre.org}}</ref> This book does not define or give examples to integer underflow.<ref>{{cite book |title=24 Deadly Sins of Software Security|last=Le Blanc|first=David|page=120}}</ref>
Apple's developer's guide similarly uses the term in a section titled, "Avoiding Integer Overflows and Underflows" but then the section examines overflows without defining or talking about integer underflows.<ref>{{cite web |url=https://developer.apple.com/library/content/documentation/Security/Conceptual/SecureCodingGuide/Articles/BufferOverflows.html#//apple_ref/doc/uid/TP40002577-SW7 |title=Avoiding Buffer Overflows and Underflows |website=developer.apple.com}}</ref> This term can also be found in bug reports and changelogs. The term maybe used improperly by the bug reporter or inexperienced engineer. These always result in a fix that is explained by another known error type such as overflow, array boundary, or improper casting.<ref>{{cite web |url=https://www.mozilla.org/en-US/security/advisories/mfsa2015-147/ |title=Integer underflow and buffer overflow processing MP4 metadata in libstagefright |website=Mozilla}}</ref> Although underflow is not possible on integer operations, [[arithmetic underflow]] is possible on [[Floating-point arithmetic|floating-point operations]].
 
When the ideal result of an operation is not an exact integer, the meaning of overflow can be ambiguous in edge cases. Consider the case where the ideal result has a value of 127.25 and the output type's maximum representable value is 127. If overflow is defined as the ideal value being outside the representable range of the output type, then this case would be classified as an overflow. For operations that have well defined rounding behavior, overflow classification may need to be postponed until after rounding is applied. The C11 standard<ref name="auto"/> defines that conversions from floating point to integer must round toward zero. If C is used to convert the floating point value 127.25 to integer, then rounding should be applied first to give an ideal integer output of 127. Since the rounded integer is in the outputs range, the C standard would not classify this conversion as an overflow.
 
==Inconsistent behavior==
The behavior on occurrence of overflow may not be consistent in all circumstances. For example, in the language [[Rust (programming language)|Rust]], while functionality is provided to give users choice and control, the behavior for basic use of mathematic operators is naturally fixed; however, this fixed behavior differs between a program built in 'debug' mode and one built in 'release' mode.<ref>{{Cite web |title=Operator expressions - The Rust Reference |url=https://doc.rust-lang.org/stable/reference/expressions/operator-expr.html#overflow |website=Rust-lang.org |access-date=2021-02-12}}</ref> In C, unsigned integer overflow is defined to wrap around, while signed integer overflow causes [[undefined behavior]].
 
==Methods to address integer overflow problems==
{| class="wikitable" style="float:right; margin-left:1em; margin-right:0; width:30%;"
|+ Integer overflow handling in various programming languages
|-
! Language
! Unsigned integer
! Signed integer
|-
| [[Ada (programming language)|Ada]] || modulo the type's modulus || <samp>'''raise''' Constraint_Error</samp>
|-
| [[C (programming language)|C]], [[C++]] || modulo power of two || undefined behavior
|-
| [[C Sharp (programming language)|C#]] || colspan="2" | modulo power of 2 in unchecked context; <code>System.OverflowException</code> is raised in checked context<ref>{{cite web |url=http://msdn.microsoft.com/en-us/library/khy08726.aspx |title=Checked and Unchecked (C# Reference) |last=BillWagner |website=msdn.microsoft.com|date=8 April 2023 }}</ref>
|-
| [[Java (programming language)|Java]] || modulo power of two (char is the only unsigned primitive type in Java) || modulo power of two
|-
| [[JavaScript]] || colspan="2" | all numbers are [[Double-precision floating-point format|double-precision floating-point]] except the new [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt BigInt]
|-
| [[MATLAB]] || colspan="2" | Builtin integers saturate. Fixed-point integers configurable to wrap or saturate
|-
| [[Python (programming language)|Python]] 2 || {{N/A}} || convert to <var>long</var> type (bigint)
|-
| [[Seed7]] || {{N/A}} || <samp>'''raise''' OVERFLOW_ERROR</samp><ref>[https://seed7.sourceforge.net/manual/errors.htm#OVERFLOW_ERROR Seed7 manual], section 16.3.3 OVERFLOW_ERROR.</ref>
|-
| [[Scheme (programming language)|Scheme]] || {{N/A}} || convert to bigNum
|-
| [[Simulink]] || colspan="2" | configurable to wrap or saturate
|-
| [[Smalltalk]] || {{N/A}} || convert to LargeInteger
|-
| [[Swift (programming language)|Swift]] || colspan="2" | Causes error unless using special overflow operators.<ref>The Swift Programming Language. Swift 2.1 Edition. October 21, 2015.</ref>
|-
|}
 
===Detection===
Run-time overflow detection implementation <code>UBSan</code> ([[undefined behavior]] sanitizer) is available for [[C compiler]]s.
 
In Java 8, there are [[Function overloading|overloaded methods]], for example {{Javadoc:SE|member=addExact(int, int)|java/lang|Math|addExact(int,int)}}, which will throw an {{Javadoc:SE|java/lang|ArithmeticException}} in case of overflow.
 
[[Computer emergency response team]] (CERT) developed the As-if Infinitely Ranged (AIR) integer model, a largely automated mechanism to eliminate integer overflow and truncation in C/C++ using run-time error handling.<ref>[http://www.cert.org/archive/pdf/09tn023.pdf As-if Infinitely Ranged Integer Model]</ref>
 
===Avoidance===
By allocating variables with data types that are large enough to contain all values that may possibly be computed and stored in them, it is always possible to avoid overflow. Even when the available space or the fixed data types provided by a programming language or environment are too limited to allow for variables to be defensively allocated with generous sizes, by carefully ordering operations and checking operands in advance, it is often possible to ensure ''a priori'' that the result will never be larger than can be stored. [[Static program analysis|Static analysis]] tools, [[formal verification]] and [[design by contract]] techniques can be used to more confidently and robustly ensure that an overflow cannot accidentally result.
 
===Handling===
If it is anticipated that overflow may occur, then tests can be inserted into the program to detect when it happens, or is about to happen, and do other processing to mitigate it. For example, if an important result computed from user input overflows, the program can stop, reject the input, and perhaps prompt the user for different input, rather than the program proceeding with the invalid overflowed input and probably malfunctioning as a consequence.
 
[[Central processing unit|CPUs]] generally have a way to detect this to support addition of numbers larger than their register size, typically using a status bit. The technique is called multiple-precision arithmetic. Thus, it is possible to perform byte-wide addition on operands wider than a byte: first add the low bytes, store the result and check for overflow; then add the high bytes, and if necessary add the ''carry'' from the low bytes, then store the result.
 
Handling possible overflow of a calculation may sometimes present a choice between performing a check ''before'' a calculation (to determine whether or not overflow is going to occur), or ''after'' it (to consider whether or not it likely occurred based on the resulting value). Since some implementations might generate a [[interrupt|trap]] condition on integer overflow, the most portable programs test in advance of performing the operation that might overflow.
 
===Programming language support===
Programming languages implement various mitigation methods against an accidental overflow: [[Ada (programming language)|Ada]], [[Seed7]], and certain variants of functional languages trigger an exception condition on overflow, while [[Python (programming language)|Python]] (since 2.4) seamlessly converts internal representation of the number to match its growth, eventually representing it as <code>long</code> – whose ability is only limited by the available memory.<ref>[https://docs.python.org/2/reference/expressions.html Python documentation], section 5.1 Arithmetic conversions.</ref>
 
In languages with native support for [[arbitrary-precision arithmetic]] and [[type safety]] (such as [[Python (programming language)|Python]], [[Smalltalk]], or [[Common Lisp]]), numbers are promoted to a larger size automatically when overflows occur, or exceptions thrown (conditions signaled) when a range constraint exists. Using such languages may thus be helpful to mitigate this issue. However, in some such languages, situations are still possible where an integer overflow can occur. An example is explicit optimization of a code path which is considered a bottleneck by the profiler. In the case of [[Common Lisp]], this is possible by using an explicit declaration to type-annotate a variable to a machine-size word (fixnum)<ref>{{cite web |url=http://www.lispworks.com/documentation/HyperSpec/Body/d_type.htm |title=''Declaration'' '''TYPE''' |website=Common Lisp HyperSpec}}</ref> and lower the type safety level to zero<ref>{{cite web |url=http://www.lispworks.com/documentation/HyperSpec/Body/d_optimi.htm |title=''Declaration'' '''OPTIMIZE''' |website=Common Lisp HyperSpec}}</ref> for a particular code block.<ref name="reddy">{{cite web
|last=Reddy |first=Abhishek
|date=2008-08-22
|url=http://random-state.net/features-of-common-lisp.html
|title=Features of Common Lisp
}}</ref><ref>{{Cite book |last=Pierce |first=Benjamin C. |author-link=Benjamin C. Pierce |title=Types and Programming Languages |publisher=MIT Press |year=2002 |isbn=0-262-16209-1 |url=http://www.cis.upenn.edu/~bcpierce/tapl/}}</ref><ref>{{Cite journal |last1=Wright |first1=Andrew K. |last2=Felleisen |first2=Matthias |author2-link=Matthias Felleisen |year=1994 |title=A Syntactic Approach to Type Soundness |journal=Information and Computation |volume=115 |issue=1 |pages=38–94 |url=http://citeseer.ist.psu.edu/wright92syntactic.html |doi=10.1006/inco.1994.1093 |doi-access=free}}</ref><ref>{{Cite journal |last=Macrakis |first=Stavros |date=April 1982 |title=Safety and power |journal=ACM SIGSOFT Software Engineering Notes |volume=7 |issue=2 |pages=25–26 |doi=10.1145/1005937.1005941 |s2cid=10426644}}</ref>
 
In stark contrast to older languages such as C, some newer languages such as [[Rust (programming language)|Rust]] provide built-in functions that allow easy detection and user choice over how overflow should be handled case-by-case. In Rust, while use of basic mathematic operators naturally lacks such flexibility, users can alternatively perform calculations via a set of methods provided by each of the integer primitive types. These methods give users several choices between performing a ''checked'' (or ''overflowing'') operation (which indicates whether or not overflow occurred via the return type); an 'unchecked' operation; an operation that performs wrapping, or an operation which performs saturation at the numeric bounds.
 
===Saturated arithmetic===
In [[computer graphics]] or [[signal processing]], it is typical to work on data that ranges from 0 to 1 or from −1 to 1. For example, take a [[grayscale]] image where 0 represents black, 1 represents white, and the values in between represent shades of gray. One operation that one may want to support is brightening the image by multiplying every [[pixel]] by a constant. [[Saturated arithmetic]] allows one to just blindly multiply every pixel by that constant without worrying about overflow by just sticking to a reasonable outcome that all these pixels larger than 1 (i.e., [[high-dynamic-range imaging|"brighter than white"]]) just become white and all values "darker than black" just become black.
 
==Examples==
Unanticipated arithmetic overflow is a fairly common cause of [[software bug|program errors]]. Such overflow bugs may be hard to discover and diagnose because they may manifest themselves only for very large input data sets, which are less likely to be used in validation tests.
 
Taking the arithmetic mean of two numbers by adding them and dividing by two, as done in many [[search algorithm]]s, causes error if the sum (although not the resulting mean) is too large to be represented and hence overflows.<ref>{{cite web |url=http://googleresearch.blogspot.co.uk/2006/06/extra-extra-read-all-about-it-nearly.html |title=Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken |website=googleresearch.blogspot.co.uk|date=2 June 2006 }}</ref>
 
Between 1985 and 1987, arithmetic overflow in the [[Therac-25]] [[radiation therapy]] machines, along with a lack of hardware safety controls, caused the death of at least six people from radiation overdoses.<ref>{{Cite web |last=Beuhler |first=Patrick |date=2021-07-05 |title=When Small Software Bugs Cause Big Problems |url=https://blog.grio.com/2021/07/when-small-software-bugs-cause-big-problems.html |access-date=2023-07-16 |website=Grio Blog |language=en-US}}</ref>
 
An unhandled arithmetic overflow in the engine steering software was the primary cause of the crash of the 1996 maiden flight of the [[Ariane 5 Flight 501|Ariane 5]] rocket.<ref>{{cite web |last=Gleick |first=James |author-link=James Gleick |date=1 December 1996 |title=A Bug and A Crash |url=https://www.nytimes.com/1996/12/01/magazine/little-bug-big-bang.html |work=The New York Times |access-date=17 January 2019}}</ref> The software had been considered bug-free since it had been used in many previous flights, but those used smaller rockets which generated lower acceleration than Ariane 5. Frustratingly, the part of the software in which the overflow error occurred was not even required to be running for the Ariane 5 at the time that it caused the rocket to fail: it was a launch-regime process for a smaller predecessor of the Ariane 5 that had remained in the software when it was adapted for the new rocket. Further, the true cause of the failure was a flaw in the engineering specification of how the software dealt with the overflow when it was detected: it did a diagnostic dump to its bus, which would have been connected to test equipment during software testing during development but was connected to the rocket steering motors during flight; the data dump drove the engine nozzle hard to one side which put the rocket out of aerodynamic control and precipitated its rapid breakup in the air.<ref>Official report of Ariane 5 launch failure incident.</ref>
 
On 30 April 2015, the U.S. [[Federal Aviation Administration]] announced it will order [[Boeing 787]] operators to reset its electrical system periodically, to avoid an integer overflow which could lead to loss of electrical power and [[ram air turbine]] deployment, and Boeing deployed a [[software update]] in the fourth quarter.<ref>{{cite news |title= F.A.A. Orders Fix for Possible Power Loss in Boeing 787 |first=Jad |last=Mouawad |work=[[New York Times]] |date= 30 April 2015 |url= https://www.nytimes.com/2015/05/01/business/faa-orders-fix-for-possible-power-loss-in-boeing-787.html?_r=0}}</ref> The [[European Aviation Safety Agency]] followed on 4 May 2015.<ref>{{cite web |url= http://ad.easa.europa.eu/ad/US-2015-09-07 |work=Airworthiness Directives |title=US-2015-09-07: Electrical Power – Deactivation |date=4 May 2015 |publisher=[[European Aviation Safety Agency]]}}</ref> The error happens after 2<sup>31</sup> hundredths of a second (about {{#expr:ceil(2^31/100/3600/24)}} days), indicating a 32-bit [[Signed number representations|signed]] [[Integer (computer science)|integer]].
 
Overflow bugs are evident in some computer games. In ''[[Super Mario Bros.]]'' for the [[NES]], the stored number of lives is a signed byte (ranging from −128 to 127) meaning the player can safely have 127 lives, but when the player reaches their 128th life, the counter rolls over to zero lives (although the number counter is glitched before this happens) and stops keeping count. As such, if the player then dies it's an immediate game over. This is caused by the game's data overflow that was an error of programming as the developers may not have thought said number of lives would be reasonably earned in a full playthrough.{{citation needed|date=February 2025}}
 
In the arcade game ''[[Donkey Kong (arcade game)|Donkey Kong]]'', it is impossible to advance past level 22 due to an integer overflow in its time/bonus. The game calculates the time/bonus by taking the level number a user is on, multiplying it by 10, and adding 40. When they reach level 22, the time/bonus number is 260, which is too large for its 8-bit 256 value register, so it overflows to a value of 4 – too short to finish the level. In ''[[Donkey Kong Jr. Math]]'', when trying to calculate a number over 10,000, it shows only the first 4 digits. Overflow is the cause of the famous [[kill screen|"split-screen" level]] in ''[[Pac-Man]]''.<ref>{{cite web |url=http://home.comcast.net/~jpittman2/pacman/pacmandossier.html |title=The Pac-Man Dossier |last=Pittman |first=Jamey}}</ref> Such a bug also caused the ''Far Lands'' in ''[[Minecraft]]'' Java Edition which existed from the Infdev development period to Beta 1.7.3; it was later fixed in Beta 1.8. The same bug also existed in ''Minecraft'' Bedrock Edition but has since been fixed.<ref>{{cite web |url=https://minecraft.wiki/w/Far_Lands |title=Far Lands |website=Minecraft Wiki |access-date=24 September 2023 |language=en}}</ref>{{unreliable source|date=October 2024}}
 
[[File:Error message due to an integer signedness bug in the stack setup code of MASM 1.00.gif|thumb|An integer signedness bug in the stack setup code emitted by the [[Pascal (programming language)|Pascal]] compiler prevented IBM–[[Microsoft Macro Assembler]] (MASM) version 1.00, a [[DOS]] program from 1981, and many other programs compiled with the same compiler, to run under some configurations with more than 512 KiB of memory.]]
 
IBM–[[Microsoft Macro Assembler]] (MASM) version 1.00, and likely all other programs built by the same [[Pascal (programming language)|Pascal]] compiler, had an integer overflow and signedness error in the stack setup code, which prevented them from running on newer [[DOS]] machines or emulators under some common configurations with more than 512&nbsp;KiB of memory. The program either hangs or displays an error message and exits to DOS.<ref>{{cite web |last=Lenclud |first=Christophe |url=https://slions.net/threads/debugging-the-ibm-personal-computer-macro-assembler-masm-version-1-00.33/ |title=Debugging IBM MACRO Assembler Version 1.00|date=21 April 2017 }}</ref>
 
In August 2016, a [[casino]] machine at [[Resorts World]] casino printed a prize ticket of $42,949,672.76 as a result of an overflow bug. The casino refused to pay this amount, calling it a malfunction, using in their defense that the machine clearly stated that the maximum payout was $10,000, so any prize exceeding that had to be the result of a programming bug. The [[New York State Gaming Commission]] ruled in favor of the casino.<ref>{{cite web |last=Kravets |first=David |date=June 15, 2017 |url=https://arstechnica.com/tech-policy/2017/06/sorry-maam-you-didnt-win-43m-there-was-a-slot-machine-malfunction |title=Sorry ma'am you didn't win $43M – there was a slot machine 'malfunction' |website=Ars Technica}}</ref>
 
==See also==
*[[ArithmeticCarry overflow(arithmetic)]]
*[[SIGFPEModular arithmetic]]
*[[BufferNuclear overflowGandhi]]
*[[Heap overflow]]
*[[Pointer swizzling]]
*[[Software testing]]
*[[Static code analysis]]
 
==External linksReferences==
{{Reflist}}
*[http://www.phrack.org/archives/60/p60-0x0a.txt Phrack #60, Basic Integer Overflows]
*[http://www.phrack.org/archives/60/p60-0x09.txt Phrack #60, Big Loop Integer Protection]
 
==External links==
[[Category:Programming bugs]]
*[http://www.phrack.org/issues.html?issue=60&id=10#article Phrack #60, Basic Integer Overflows]
[[Category:Security exploits]]
*[http://www.phrack.org/issues.html?issue=60&id=9#article Phrack #60, Big Loop Integer Protection]
*[https://web.archive.org/web/20121010025025/http://www.cs.cmu.edu/~dbrumley/pubs/integer-ndss-07.pdf Efficient and Accurate Detection of Integer-based Attacks]
*[http://projects.webappsec.org/Integer-Overflows WASC Threat Classification – Integer Overflows]
*[http://www.cs.utah.edu/~regehr/papers/tosem15.pdf Understanding Integer Overflow in C/C++]
*[https://www.allaboutcircuits.com/textbook/digital/chpt-2/binary-overflow/ Binary Overflow – Binary Arithmetic]
*[https://webstore.ansi.org/RecordDetail.aspx?sku=ISO%2FIEC%209899:2011 ISO C11 Standard]
 
[[Category:Software bugs]]
[[de:Ganzzahlüberlauf]]
[[Category:Computer security exploits]]
[[pl:Integer overflow]]
[[Category:Computer arithmetic]]
[[de:Arithmetischer Überlauf]]