...
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 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, 284, 581, 634, 1434, 0240, 0241, 0246, 0551, 0601, | Partially implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...