MISRA C:2012 Rule 7.4

A string literal shall not be assigned to an object unless the object’s type is “pointer to const-qualified char”

Description

Rule Definition

A string literal shall not be assigned to an object unless the object’s type is “pointer to const-qualified char”.

Rationale

This rule prevents assignments that allow modification of a string literal.

An attempt to modify a string literal can result in undefined behavior. For example, some implementations can store string literals in read-only memory. An attempt to modify the string literal can result in an exception or crash.

Polyspace Implementation

The rule checker flags assignment of string literals to:

  • Pointers with data type other than const char*.

  • Arrays with data type other than const char.

Troubleshooting

If you expect a rule violation but do not see it, refer to Coding Standard Violations Not Displayed.

Examples

expand all

char *str1 = "xxxxxx";            // Non-Compliant 
const char *str2 = "xxxxxx";      // Compliant 

void checkSystem1(char*);
void checkSystem2(const char*);

void main() {
 checkSystem1("xxxxxx");    // Non-Compliant 
 checkSystem2("xxxxxx");    // Compliant 
}

In this example, the rule is not violated when string literals are assigned to const char* pointers, either directly or through copy of function arguments. The rule is violated only when the const qualifier is not used.

Check Information

Group: Literals and Constants
Category: Required
AGC Category: Required
Introduced in R2014b