A string literal is a sequence of zero or more multibyte characters enclosed in double quotes ("xyz", for example). A wide string literal is the same, except prefixed by the letter 'L' (L"xyz", for example).
At compile time, string literals are used to create an array of static storage duration of sufficient length to contain the character sequence and a null-termination character. It is unspecified whether these arrays are distinct. The behavior is undefined if a program attempts to modify string literals but frequently results in an access violation, as string literals are typically stored in read-only memory.
Do not attempt to modify a string literal. Use a named array of characters to obtain a modifiable string.
In this non-compliant code example, the char pointer p is initialized to the address of a string literal. Attempting to modify the string literal results in undefined behavior.
char *p = "string literal"; p[0] = 'S'; |
As an array initializer, a string literal specifies the initial values of characters in an array as well as the size of the array (see STR36-C. Do not specify the dimension of a character array initialized with a string literal). This code creates a copy of the string literal in the space allocated to the character array a. The string stored in a can be safely modified.
char a[] = "string literal"; a[0] = 'S'; |
In this non-compliant example, the mktemp() function modifies its string argument.
mktemp("/tmp/edXXXXXX");
|
Instead of passing a string literal, use a named array:
static char fname[] = "/tmp/edXXXXXX"; mktemp(fname); |
Modifying string literals can lead to abnormal program termination and possibly denial-of-service attacks.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
STR30-C |
low |
likely |
low |
P9 |
L2 |
The LDRA tool suite V 7.6.0 is able to detect violations of this rule.
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.4.5, "String literals" \[[Summit 95|AA. C References#Summit 95]\] comp.lang.c FAQ list - Question 1.32 \[[Plum 91|AA. C References#Plum 91]\] Topic 1.26, "strings - string literals" |
STR07-A. Use TR 24731 for remediation of existing string manipulation code 07. Characters and Strings (STR)