Main Content

AUTOSAR C++14 Rule A2-13-4

String literals shall not be assigned to non-constant pointers

Description

Rule Definition

String literals shall not be assigned to non-constant pointers.

Rationale

This rule prevents assignments of string literals to pointers that point to non const objects. Such assignments allow later modification of the 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.

Later C++ standards require a compiler warning for such modifications. The rule is in place for situations when you suppress compiler warnings (and AUTOSAR C++14 rules associated with those warnings).

Polyspace Implementation

The rule checker flags assignment of string literals to pointers other than pointers to const objects.

The checker does not flag assignment of string literals to non-const arrays. The checker for AUTOSAR C++ 14 Rule A18-1-1 forbids direct use of C-style arrays and prevents these assignments.

Troubleshooting

If you expect a rule violation but Polyspace® does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

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: Lexical conventions
Category: Required, Automated

Version History

Introduced in R2019a