Skip to content

Commit 5d89872

Browse files
committed
C++: Add the examples to the test.
1 parent 1343e4c commit 5d89872

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/UnsignedDifferenceExpressionComparedZero.expected

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,4 @@
1313
| test.cpp:266:10:266:24 | ... > ... | Unsigned subtraction can never be negative. |
1414
| test.cpp:276:11:276:19 | ... > ... | Unsigned subtraction can never be negative. |
1515
| test.cpp:288:10:288:18 | ... > ... | Unsigned subtraction can never be negative. |
16+
| test.cpp:312:9:312:25 | ... > ... | Unsigned subtraction can never be negative. |

cpp/ql/test/query-tests/Security/CWE/CWE-191/UnsignedDifferenceExpressionComparedZero/test.cpp

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ void test(unsigned x, unsigned y, bool unknown) {
4343
while(cond()) {
4444
if(unknown) { y--; }
4545
}
46-
46+
4747
if(x - y > 0) { } // GOOD
4848

4949
x = y;
@@ -298,3 +298,26 @@ int test18() {
298298

299299
return (a - b > 0); // GOOD (as b = 0)
300300
}
301+
302+
typedef unsigned int uint32_t;
303+
typedef long long int64_t;
304+
uint32_t get_limit();
305+
uint32_t get_data();
306+
307+
void test19() {
308+
// from the doc:
309+
uint32_t limit = get_limit();
310+
uint32_t total = 0;
311+
312+
while (limit - total > 0) { // BAD: if `total` is greater than `limit` this will underflow and continue executing the loop.
313+
total += get_data();
314+
}
315+
316+
while (total < limit) { // GOOD: never underflows here because there is no arithmetic.
317+
total += get_data();
318+
}
319+
320+
while ((int64_t)limit - total > 0) { // GOOD: never underflows here because the result always fits in an `int64_t`.
321+
total += get_data();
322+
}
323+
}

0 commit comments

Comments
 (0)