If a constant value is given for a given an identifier, do not diminish the modifiability maintainability of the code in which it is used by assuming its value in expressions. Just Simply giving the constant a name is not enough to ensure modifiability; you must be careful to always to use the name, and remember that the value could change.
Non-Compliant Coding Example
can change. This recommendation is related to DCL06-C. Use meaningful symbolic constants to represent literal values.
Noncompliant Code Example
The header stdio.h
defines the BUFSIZ
macro, which expands to an integer constant expression that is the size of the buffer used by the setbuf()
function. This noncompliant code This non-compliant coding example defeats the purpose of defining BUFSIZ
as a constant by assuming its value in the following expression:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> /* ... */ nblocks = 1 + ((nbytes - 1) >> 9); /* hardBUFSIZ to= modify,512 uses= "magic2^9 number" */ |
The programmer's assumption underlying this code is that "everyone knows that BUFSIZ
equals 512," and right-shifting nine 9 bits is the same (for positive numbers) as dividing by 512. However, if BUFSIZ
changes to 1024 on some systems, modifications are difficult and error - prone.
Compliant Solution
This compliant solution uses the identifier assigned to the constant value in the expression.:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdio.h> /* ... */ nblocks = 1 + (nbytes - 1) / BUFSIZ; |
Most modern C compilers will optimize this code appropriately.
References
Risk Assessment
Assuming the value of an expression diminishes the maintainability of code and can produce unexpected behavior under any circumstances in which the constant changes.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP07-C | Low | Unlikely | Medium | P2 | L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Axivion Bauhaus Suite |
| CertC-EXP07 | |||||||
Helix QAC |
| C3120, C3121, C3122, C3123, C3131, C3132 | |||||||
LDRA tool suite |
| 201 S | Fully implemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ Coding Standard | VOID EXP07-CPP. Do not diminish the benefits of constants by assuming their values in expressions |
Bibliography
[Plum 1985] | Rule 1-5 |
...
\[[Plum 85|AA. C References#Plum 85]\] Rule 1-5
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.10, "Preprocessing directives," and Section 5.1.1, "Translation environment" Wiki Markup