Skip to content

Commit ad4cd6f

Browse files
committed
[zlaski/bad-addition-qhelp-reword] Initial change.
1 parent 219fcb7 commit ad4cd6f

File tree

2 files changed

+9
-6
lines changed

2 files changed

+9
-6
lines changed

cpp/ql/src/Likely Bugs/Arithmetic/BadAdditionOverflowCheck.qhelp

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@
66
<p>
77
Checking for overflow of integer addition needs to be done with
88
care, because automatic type promotion can prevent the check
9-
from working correctly.
9+
from working as intended, with the same value (<code>true</code>
10+
or <code>false</code>) always being returned.
1011
</p>
1112
</overview>
1213
<recommendation>
@@ -18,15 +19,16 @@
1819
<example>
1920
<sample src="BadAdditionOverflowCheckExample1.cpp" />
2021
<p>
21-
On a typical architecture where <tt>short</tt> is 16 bits
22-
and <tt>int</tt> is 32 bits, the operands of the addition are
23-
automatically promoted to <tt>int</tt>, so it cannot overflow
22+
On a typical architecture where <code>short</code> is 16 bits
23+
and <code>int</code> is 32 bits, the operands of the addition are
24+
automatically promoted to <code>int</code>, so it cannot overflow
2425
and the result of the comparison is always false.
2526
</p>
2627
<p>
2728
The code below implements the check correctly, by using an
2829
explicit cast to make sure that the result of the addition
29-
is <tt>unsigned short</tt>.
30+
is <code>unsigned short</code> (which may overflow, in which case
31+
the comparison would evaluate to <code>true</code>).
3032
</p>
3133
<sample src="BadAdditionOverflowCheckExample2.cpp" />
3234
</example>
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
bool checkOverflow(unsigned short x, unsigned short y) {
2-
return (x + y < x); // BAD: x and y are automatically promoted to int.
2+
// BAD: comparison is always false due to type promotion
3+
return (x + y < x);
34
}

0 commit comments

Comments
 (0)