55<overview >
66<p >
77When checking for integer overflow, you may often write tests like
8- <code >a + b < a </code >. This works fine if <code >a </code > and
9- <code >b </code > are unsigned integers, since any overflow in the addition
8+ <code >p + i < p </code >. This works fine if <code >p </code > and
9+ <code >i </code > are unsigned integers, since any overflow in the addition
1010will cause the value to simply "wrap around." However, using this pattern when
11- <code >a </code > is a pointer is problematic because pointer overflow has
11+ <code >p </code > is a pointer is problematic because pointer overflow has
1212undefined behavior according to the C and C++ standards. If the addition
1313overflows and has an undefined result, the comparison will likewise be
1414undefined; it may produce an unintended result, or may be deleted entirely by an
@@ -18,13 +18,13 @@ optimizing compiler.
1818</overview >
1919<recommendation >
2020<p >
21- To check whether an index <code >a </code > is less than the length of an array,
22- simply compare these two numbers as unsigned integers: <code >a < ARRAY_LENGTH</code >.
21+ To check whether an index <code >i </code > is less than the length of an array,
22+ simply compare these two numbers as unsigned integers: <code >i < ARRAY_LENGTH</code >.
2323If the length of the array is defined as the difference between two pointers
24- <code >ptr</code > and <code >p_end</code >, write <code >a < p_end - ptr</code >.
25- If a is <code >signed</code >, cast it to <code >unsigned</code >
26- in order to guard against negative <code >a </code >. For example, write
27- <code >(size_t)a < p_end - ptr</code >.
24+ <code >ptr</code > and <code >p_end</code >, write <code >i < p_end - ptr</code >.
25+ If i is <code >signed</code >, cast it to <code >unsigned</code >
26+ in order to guard against negative <code >i </code >. For example, write
27+ <code >(size_t)i < p_end - ptr</code >.
2828</p >
2929</recommendation >
3030<example >
@@ -41,14 +41,14 @@ overflows and wraps around.
4141<p >
4242In both of these checks, the operations are performed in the wrong order.
4343First, an expression that may cause undefined behavior is evaluated
44- (<code >ptr + a </code >), and then the result is checked for being in range.
44+ (<code >ptr + i </code >), and then the result is checked for being in range.
4545But once undefined behavior has happened in the pointer addition, it cannot
4646be recovered from: it's too late to perform the range check after a possible
4747pointer overflow.
4848</p >
4949
5050<p >
51- While it's not the subject of this query, the expression <code >ptr + a <
51+ While it's not the subject of this query, the expression <code >ptr + i <
5252ptr_end</code > is also an invalid range check. It's undefined behavor in
5353C/C++ to create a pointer that points more than one past the end of an
5454allocation.
0 commit comments