Skip to content

Commit c6d848c

Browse files
author
Robert Marsh
committed
C++: simplify PointerOverflow.qhelp
1 parent 81262d5 commit c6d848c

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

cpp/ql/src/Likely Bugs/Memory Management/PointerOverflow.qhelp

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,19 +4,17 @@
44
<qhelp>
55
<overview>
66
<p>
7-
The expression <code>ptr + a &lt; ptr</code> is equivalent to <code>a &lt;
8-
0</code>, and an optimizing compiler is likely to make that replacement,
9-
thereby removing a range check that might have been necessary for security.
10-
If <code>a</code> is known to be non-negative, the compiler can even replace <code>ptr +
11-
a &lt; ptr</code> with <code>false</code>.
7+
When checking for integer overflow, you may often write tests like
8+
<code>a + b &lt; a</code>. This works fine if <code>a</code> and
9+
<code>b</code> are unsigned integers, since any overflow in the addition
10+
will 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
12+
undefined behavior according to the C and C++ standards. If the addition
13+
overflows and has an undefined result, the comparison will likewise be
14+
undefined; it may produce an unintended result, or may be deleted entirely by an
15+
optimizing compiler.
1216
</p>
1317

14-
<p>
15-
The reason is that pointer arithmetic overflow in C/C++ is undefined
16-
behavior. The optimizing compiler can assume that the program has no
17-
undefined behavior, which means that adding a positive number to <code>ptr</code> cannot
18-
produce a pointer less than <code>ptr</code>.
19-
</p>
2018
</overview>
2119
<recommendation>
2220
<p>

0 commit comments

Comments
 (0)