Main Content

MISRA C:2023 Rule 7.4

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

Since R2024a

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.

As an exception, passing a string literal to a variadic function through a variable argument list does not violate this rule.

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 Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

char *str1 = "xxxxxx";            // Noncompliant 
const char *str2 = "xxxxxx";      // Compliant 

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

void main() {
 checkSystem1("xxxxxx");    // Noncompliant 
 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.

In this example, a string literal is passed to the variadic functions foo and bar. Because the string literal is passed to foo as part of a variable argument list, Polyspace® does not report a violation. For bar, the string literal argument binds to a char*, which is not compliant with this rule. Polyspace reports a violation on bar.

extern void foo( int x, ... );

extern void bar( char *text, ... ); 

void variadic( void )
{
    foo( 42u, "String Literal" ); // Compliant by exception
    bar( "String Literal", 42u ); // Noncompliant
}

Check Information

Group: Literals and Constants
Category: Required
AGC Category: Required

Version History

Introduced in R2024a

expand all