Versions Compared

Key

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

As string String literals are constant , they and should only be assigned to constant pointers. This recommendation supports rule STR30-C.

...

Code Block
bgColor#FFcccc
char * c = "Hello"; //* Bad: assigned to non-const */
c[3] = 'a'; //* Undefined (but compiles) */

Compliant Solution 1

If you properly assign string literals to const pointers, the The compiler will not allow direct manipulation of the contents of string literals that are assignhed to const pointers.

Code Block
bgColor#ccccFF
char const * c = "Hello"; //* Good */
//c[3] = 'a'; would cause a compile error

...

Code Block
bgColor#FFcccc
char * CMUfullname = "Carnegie Mellon";

/* get school from user input and validate */

if (strcmp(school,"CMU")) {
    school = CMUfullname;
}

...

Code Block
bgColor#FFcccc
char const * CMUfullname = "Carnegie Mellon";

/* get school from user input and validate */

if (strcmp(school,"CMU")) {
    school = CMUfullname;
}

...

Code Block
bgColor#ccccFF
char const * CMUfullname = "Carnegie Mellon";

/* get school from user input and validate */

if (strcmp(school,"CMU")) {
    //assuming school is properly allocated
    strcpy(school, CMUfullname);
}

...