String literals are constant and should consequently be protected by the const
qualification. This recommendation supports rule STR30-C. Do not attempt to modify string literals.
In the following non-compliant code, the const
keyword has been omitted.
char *c = "Hello"; |
If a statement such as {{c\[0\] = 'C'}} were placed following the above declaration, the code would likely still compile cleanly, but the result of the assignment is undefined as string literals are considered constant. |
In this compliant solution, the characters referred to by the pointer c
are const
\ qualified, meaning that any attempts to assign them to different values is an error.
const char *c = "Hello"; |
In cases where the string is meant to be modified, use initialization instead of assignment. In this compliant solution, c
is a modifiable char
array which has been initialized using the contents of the corresponding string literal.
char c[] = "Hello"; |
Consequently, a statement such as {{c\[0\] = 'C'}} is valid and behaves as expected. |
Modifying string literals causes undefined behavior, resulting in abnormal program termination and denial-of-service vulnerabilities.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
STR05-A |
1 (low) |
3 (likely) |
2 (medium) |
P6 |
L2 |
The LDRA tool suite V 7.6.0 is able to detect violations of this recommendation.
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[Corfield 93|AA. C References#Corfield 93]\] \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.7.8, "Initialization" \[[Lockheed Martin 2005|AA. C References#Lockheed Martin 05]\] AV Rule 151.1 |
STR03-A. Do not inadvertently truncate a null-terminated byte string 07. Characters and Strings (STR) STR06-A. Don't assume that strtok() leaves the parse string unchanged