Immutable objects should be {{const}}\-qualified. Enforcing object immutability using {{const}}\-qualification helps ensures the correctness and security of applications. ISO/IEC PDTR 24772 \[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\], for example, recommends labeling parameters as constant to avoid the unintentional modification of function arguments. |
STR05-A. Prefer making string literals const-qualified describes a specialized case of this recommendation.
In this non-compliant code example, pi
is declared as a float
. Although pi is a mathematical constant, its value is not protected from accidental modification.
float pi = 3.14159f; float degrees; float radians; /* ... */ radians = degrees * PI / 180; |
In this compliant solution, pi
is declared as a const
-qualified object.
const float pi = 3.14159f; float degrees; float radians; /* ... */ radians = degrees * pi / 180; |
In this non-compliant code example, max
is declared as a const
-qualified object. While declaring non-integer constants as const
-qualified objects is the best that can be done in C, for integer constants we can do better. Declaring immutable integer values as const
-qualified objects still allows the programmer to take the address of the object. Also, const
-qualified integers cannot be used in locations where an integer constant is required, such as the value of a case
constant.
const int max = 15; int a[max]; /* invalid declaration outside of a function */ const int *p; p = &max; /* a const-qualified object can have its address taken */ |
Most C compilers allocate memory for const
-qualified objects.
enum
)This compliant solution declares max
as an enumeration constant rather than a const
-qualified object or a macro definition.
enum { max = 15 }; int a[max]; /* OK */ const int *p; p = &max; /* error: '&' on constant */ |
Using ordinary variables to hold constants instead of using enumeration constants or const
-qualified objects can result in a value intended to be constant being changed at runtime.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
DCL00-A |
1 (low) |
1 (unlikely) |
2 (medium) |
P2 |
L3 |
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.3.2.1, "Lvalues, arrays, and function designators," Section 6.7.2.2, "Enumeration specifiers," and Section 6.10.3, "Macro replacement" \[[ISO/IEC PDTR 24772|AA. C References#ISO/IEC PDTR 24772]\] "CSJ Passing parameters and return values" \[[Saks 00|AA. C References#Saks 00]\] Dan Saks. [Numeric Literals|http://www.embedded.com/2000/0009/0009pp.htm]. Embedded Systems Programming. September, 2000. \[[Summit 05|AA. C References#Summit 05]\] [Question 10.5b|http://c-faq.com/cpp/constvsdefine.html] |
02. Declarations and Initialization (DCL) 02. Declarations and Initialization (DCL) DCL01-A. Do not reuse variable names in subscopes