This is an extension of rule:
STR30-C. Do not attempt to modify string literals
As string literals are constant, they should only be assigned to constant pointers.
Non-Compliant Code Example 1
The const
keyword is not included in these declarations.
char* c1 = "Hello"; // Bad: assigned to non-const char c2[] = "Hello"; // Bad: assigned to non-const char c3[6] = "Hello"; // Bad: assigned to non-const c1[3] = 'a'; // Undefined (but compiles)
Compliant Solution 1
If you properly assign string literals to const
pointers, the compiler will not allow direct manipulation of the contents.
char* const c1 = "Hello"; // Good char const c2[] = "Hello"; // Good char const c3[6] = "Hello"; // Good //c1[3] = 'a'; would cause a compile error
Non-Compliant Coding Example 2.a
Though it is not compliant with the C Standard, this code executes correctly if the contents of CMUfullname
are not modified.
char* CMUfullname = "Carnegie Mellon"; /* get school from user input and validate */ if (strcmp(school,"CMU")) { school = CMUfullname; }
Non-Compliant Coding Example 2.b
Adding in the const
keyword will generate a compiler warning, as the assignment of CMUfullname
to school
discards the const
qualifier. Any modifications to the contents of scholl
after this assignment will lead to errors.
char* const CMUfullname = "Carnegie Mellon"; /* get school from user input and validate */ if (strcmp(school,"CMU")) { school = CMUfullname; }
Compliant Solution 2
The compliant solution uses the const
keyword to protect the string literal, as well as using strcpy
to copy the value of CMUfullname
into school
, allowing future modification of school
.
char* const CMUfullname = "Carnegie Mellon"; /* get school from user input and validate */ if (strcmp(school,"CMU")) { //assuming school is properly allocated above strcpy(school, CMUfullname); }
Risk Assessment
Modifying string literals causes undefined behavior, resulting in abnormal program termination and denial-of-service vulnerabilities.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
STR05-A |
1 (low) |
3 (likely) |
2(medium) |
P6 |
L2 |
References:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/1993/N0389.asc
[Lockheed Martin 2005] Lockheed Martin. Joint Strike Fighter Air Vehicle C++ Coding Standards for the System Development and Demonstration Program. Document Number 2RDU00001, Rev C. December 2005. AV Rule 151.1