Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

Code Block
bgColor#FFcccc
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)
Code Block
bgColor#ccccFF
const char* c1 = "Hello"; // Good
const char c2[] = "Hello"; // Good
const char c3\[6] = "Hello"; // Good
//c1[3] = 'a'; // Compile 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

Code Block

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

Code Block

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.

Code Block

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.

...