MISRA.STRING_LITERAL.NON_CONST.2012A string literal shall not be assigned to an object unless the object's type is "pointer to const-qualified char."
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"Category: Required Analysis: Decidable, Single Translation Unit Applies to: C90, C99 AmplificationNo attempt shall be made to modify a string literal or wide string literal directly. The result of the address-of operator, &, applied to a string literal shall not be assigned to an object unless that object’s type is “pointer to array of const-qualified char”. The same considerations apply to wide string literals. A wide string literal shall not be assigned to an object unless the object’s type is “pointer to const-qualified wchar_t”. The result of the address-of operator, &, applied to a wide string literal shall not be assigned to an object unless that object’s type is “pointer to array of const-qualified wchar_t”. RationaleAny attempt to modify a string literal results in undefined behaviour. For example, some implementations may store string literals in read-only memory in which case an attempt to modify the string literal will fail and may also result in an exception or crash. This rule, when applied in conjunction with others, prevents a string literal from being modified. It is explicitly unspecified in C99 whether string literals that share a common ending are stored in distinct memory locations. Therefore, even if an attempt to modify a string literal appears to succeed, it is possible that another string literal might be inadvertently altered. ExampleThe following example shows an attempt to modify a string literal directly. "0123456789"[0] = '*'; /* Non-compliant */ These examples show how to prevent modification of string literals indirectly. /* Non-compliant - s is not const-qualified */ char *s = "string"; /* Compliant - p is const-qualified; additional qualifiers are permitted */ const volatile char *p = "string"; extern void f1 ( char *s1 ); extern void f2 ( const char *s2 ); void g ( void ) { f1 ( "string" ); /* Non-compliant - parameter s1 is not* const-qualified */ f2 ( "string" ); /* Compliant */ } char *name1 ( void ) { return ( "MISRA" ); /* Non-compliant - return type is not* const-qualified */ } const char *name2 ( void ) { return ( "MISRA" ); /* Compliant */ } See alsoRule 11.4, Rule 11.8. |