...
| Code Block | ||||
|---|---|---|---|---|
| ||||
/* (Incorrect) Set all bits in mask to one1 */ const unsigned long mask = 0xFFFFFFFF; unsigned long flipbits(unsigned long x) { return x ^ mask; } |
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
/* (Correct) Set all bits in mask to one1 */ const unsigned long mask = -1; unsigned long flipbits(unsigned long x) { return x ^ mask; } |
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
const unsigned long mask = 0x80000000; unsigned long x; /* Initialize x */ x |= (x ^ mask) + 1; |
This code has the desired effect for implementations where unsigned long has a precision of 32 bits but not for implementations where unsigned long has a precision of 64 bits.
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
const unsigned long mask = (1UL << ((sizeof(unsigned long) * CHAR_BIT) -~(ULONG_MAX >> 1)); unsigned long x; /* Initialize x */ x |= (x ^ mask) + 1; |
Risk Assessment
Vulnerabilities are frequently introduced while porting code. A buffer overflow vulnerability may result, for example, if an incorrectly defined integer constant is used to determine the size of a buffer. It is always best to write portable code, especially when there is no performance overhead for doing so.
Recommendation | Severity | Likelihood | Detectable |
|---|
Repairable | Priority | Level |
|---|---|---|
INT17-C |
high
probable
low
P18
High | Probable | No | No | P6 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
|---|---|---|---|---|---|---|---|---|---|
| Axivion Bauhaus Suite |
| CertC-INT17 | |||||||
| Helix QAC |
| C1245 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
| SEI CERT C++ |
| Coding Standard | VOID INT17-CPP. Define integer constants in an implementation-independent manner |
Bibliography
| [Dewhurst 2002] | Gotcha #25, "#define Literals" |
| [ISO/IEC 9899:2011] | Subclause 6.2.6, "Representations of Types" Subclause 6.3.1.3, "Signed and Unsigned Integers" |
...
...