
Do not cast away a const
qualification on an object of pointer type. Casting away the const
qualification allows a program to modify the object referred to by the pointer, which may result in undefined behavior. See undefined behavior 6461 in Appendix J of the C Standard.
...
EXP05-C-EX2: A number of C standard library functions are specified to return non-const
pointers that refer to their const
-qualified arguments. When the actual arguments to such functions reference const
objects, attempting to use the returned non-const
pointers to modify the const
objects would be a violation of EXP40-C. Do not modify constant objects and would lead to undefined behavior. These functions are the following:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
For instance, in following example, the function strchr
returns an unqualified char*
that points to the terminating null character of the constant character array s
(which could be stored in ROM). Even though the pointer is not const
, attempting to modify the character it points to would lead to undefined behavior.
...
If the object is constant, the compiler may allocate storage in ROM or write-protected memory. Attempting to modify such an object may lead to a program crash or denial-of-service attack.
Recommendation | Severity | Likelihood | Detectable |
---|
Repairable | Priority | Level | |
---|---|---|---|
EXP05-C | Medium | Probable | No |
No |
P4 |
L3 |
Automated Detection
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Astrée |
| pointer-qualifier-cast-const pointer-qualifier-cast-const-implicit | Fully checked | ||||||
Axivion Bauhaus Suite |
| CertC-EXP05 | Fully implemented | ||||||
CodeSonar |
| LANG.CAST.PC.CRCQ | Cast removes const qualifier | ||||||
Compass/ROSE |
| CC2.EXP05 | Fully implemented | |||||||
GCC |
|
Can detect violations of this recommendation when the | |||||||||
Helix QAC |
| C0311, C0431 | |||||||
LDRA tool suite |
| 203 S | Fully implemented | ||||||
Parasoft C/C++test |
|
|
| CERT_C-EXP05-a | A cast shall not remove any 'const' or 'volatile' qualification from the type of a pointer or reference | |||
PC-lint Plus |
|
|
| 9005 | Partially |
supported |
Polyspace Bug Finder |
Variable qualifier is lost during conversion
| Checks for cast to pointer that removes const qualification (rec. fully supported) | ||||||||
RuleChecker |
| pointer-qualifier-cast-const pointer-qualifier-cast-const-implicit | Fully checked |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
SEI CERT C++ Coding Standard | EXP55-CPP. Do not access a cv-qualified object through a cv-unqualified type |
ISO/IEC TR 24772:2013 | Pointer Casting and Pointer Type Changes [HFC] Type System [IHN] |
MISRA C:2012 | Rule 11.8 (required) |
MITRE CWE | CWE-704, Incorrect type conversion or cast |
Bibliography
[ISO/IEC 9899:2011] | Subclause 6.7.3, "Type Qualifiers" |
...
...