You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 8 Next »

A string literal is a sequence of zero or more multibyte characters enclosed in double-quotes, for example, "xyz". A wide string literal is the same, except prefixed by the letter L, for example L"xyz".

At compile time, string literals are used to create an array of static duration and sufficient length to contain the character sequence and a null-termination character. It is unspecified wehether 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,

Non-compliant Code Example

In the following example, the char pointer p is initialized to the address of the static string. Attempting to modify the string literal result results in undefined behavior.

char *p  = "string literal";
p[0] = 'S';

Compliant Solution

As an array initializer, a string literal specifies the initial values of characters in an array (as well as the size of the array). The following 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';

Non-Compliant Code Example

In this non-compliant example, the {{mktemp()}}function modifies its string argument.

mktemp("/tmp/edXXXXXX");

Compliant Solution

Instead of passing a string literal, use a named array:

static char fname[] = "/tmp/edXXXXXX";

mktemp(fname);

Consequences

Abnormal program termination.
Denial-of-service attack.

References

  • No labels