File tree Expand file tree Collapse file tree 2 files changed +9
-6
lines changed
cpp/ql/src/Likely Bugs/Arithmetic Expand file tree Collapse file tree 2 files changed +9
-6
lines changed Original file line number Diff line number Diff line change 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 >
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 >
Original file line number Diff line number Diff line change 11bool 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}
You can’t perform that action at this time.
0 commit comments