You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 14 Next »

This is an extension of recommendation:

STR30-C. Do not attempt to modify string literals

Since string literals are constant, they should only be assigned to constant pointers as indicated below:

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)
const char* c1 = "Hello"; // Good
const char c2[] = "Hello"; // Good
const char c3[6] = "Hello"; // Good
//c1[3] = 'a'; would cause a compile error

By assigning string literals to constant pointers the compiler will warn you if you try to modify them. 

Making code reverse compatible to fit this standard sometimes breaks functionality but this is a good recommendation to follow on new code. An example of a situation where implementing this would break prior code is if a string literal is assigned to a non-const pointer as in the following example
Before changing string literals to constant pointers

char* CMUfullname = "Carnegie Mellon";
...
//take user input to determine string variable "school"
if(strcmp(school,"CMU"))
{
    school=CMUfullname;
}

This prior code works fine as long as the contents of string pointer "school" are not modified if it is assigned "CMUfullname"

If one were to simply change the declaration of the string literal "CMUfullname" to const this would be the output

const char* CMUfullname = "Carnegie Mellon";
...
//take user input to determine string variable "school"
...
if(strcmp(school,"CMU")==0)
{
    school=CMUfullname;
}

This code will give a compiler warning since the assignment of "CMUfullname" to school is discarding the const qualifier. Any modifications to the contents of school if it is assigned a constant string literal will cause error conditions.

A compliant fix to this problem would be to copy the contents of "CMUfullname" to "school" but this involves the extra step of making sure school has the appropriate storage to hold it.

const char* CMUfullname = "Carnegie Mellon";
...
//take user input to determine string variable "school"
...
if(strcmp(school,"CMU")==0)
{
      strcpy(school,CMUfullname);

}

This example has shown that remedying this situation in legacy code is not necessarily simple.


Risk Assessment

Modifying string literals can lead to abnormal program termination and results in undefined behavior that can be used in denial-of-service attacks.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

STR30-C

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

  • No labels