...
This noncompliant code example uses the complement operator in the test for unsigned integer overflow. It assumes both numbers are nonnegative:
Code Block | ||||
---|---|---|---|---|
| ||||
unsignedsigned int uisi; unsignedsigned int ui2si2; unsignedsigned int sum; if (~uisi < 0 || si2 < 0) { /* Handle error condition */ } if (~si < ui2si2) { /* Handle error condition */ } sum = uisi + ui2si2; |
This code assumes that the implementation uses two's complement representation. This assumption is commonly true but is not guaranteed by the standard.
This code sample also violates INT14-C. Avoid performing bitwise and arithmetic operations on the same data.
...
This compliant solution implements a strictly conforming test for unsigned overflow:
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int uisi; unsigned int ui2si2; unsigned int sum; if (si < 0 || si2 < 0) { /* Handle error condition */ } if (UINTINT_MAX - uisi < ui2si2) { /* Handle error condition */ } sum = uisi + ui2si2; |
If the noncompliant form of this test is truly faster, talk to your compiler vendor because, if these tests are equivalent, optimization should occur. If both forms have the same performance, prefer the portable form.
...
Tool | Version | Checker | Description | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Helix QAC |
| C0202, C0240, C0241, C0242, C0243, C0246, C0284, C0551, C0581, C0601, C0633, C0634, C0635, C0660, C0662, C0830, C0831, C0840, C0899, C1001, C1002, C1003, C1006, C1008, C1012, C1014, C1015, C1019, C1020, C1021, C1022, C1026, C1028, C1029, C1034, C1035, C1036, C1037, C1038, C1041, C1042, C1043, C1044, C1045, C1046, C1434, C3664 | |||||||||||||
LDRA tool suite |
| 17 D, 69 S, 42 S | Partially implemented | ||||||||||||
Parasoft C/C++test |
| CERT_C-MSC14-a | Evaluation of constant unsigned integer expressions should not lead to wrap-around | PRQA QA-C | |||||||||||
Include Page | PRQA QA-C_v | PRQA QA-C_v | 0202, 0240, 0241, 0242, 0243, 0246, 0284, 0551, 0581, 0601, 0633, 0634, 0635, 0660, 0662, 0830, 0831, 0840, 0899, 1001, 1002, 1003, 1006, 1008, 1012, 1014, 1015, 1019, 1020, 1021, 1022, 1026, 1028, 1029, 1034, 1035, 1036, 1037, 1038, 1041, 1042, 1043, 1044, 1045, 1046, 1434, 3664 | Partially implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...