0

I understand that char pointers initialized to string literals are stored in read-only memory. But what about arrays of string literals?

In the array:

int main(void) {
char *str[] = {"hello", "world"};
}

Are "hello" and "world" stored as string literals in read-only memory? Or on the stack?

2
  • 6
    "char pointers initialized to string literals are stored in read-only memory" The literals themselves are, not the pointers. Commented Oct 6, 2022 at 8:27
  • Yes, they're stored in read-only memory too, the array doesn't change this. This only changes when you copy the literal into an array of chars. Commented Oct 6, 2022 at 8:28

2 Answers 2

4

Technically, a string literal is a quoted string in source code. Colloquially, people use “string literal” to refer to the array of characters created for a string literal. Often we can overlook this informality, but, when asking about storage, we should be clear.

The array created for a string literal has static storage duration, meaning it exists (notionally, in the abstract computer the C standard uses as a model of computing) for the entire execution of the program. Because the behavior of attempting to modify the elements of this array is not defined by the C standard, the C implementation may treat them as constants and may place them in read-only memory. It is not required to do so by the C standard, but this is common practice in C implementations for general-purpose multi-user operating systems.

In the code you show, string literals are used as initializers for an array of pointers. In this use, the array of each string literal is converted to a pointer to its first element, and that address is used as the initial value for the corresponding element of the array of pointers.

The array of the string literal is the same as for any string literal; the C implementation may place it in read-only memory, and common practice is to do so.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is what the c17 standard says:

String literals [...] It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined. (6.4.5 p 7)

Like string literals, const-qualified compound literals can be placed into read-only memory and can even be shared. (6.5.2.5 p 13).

2 Comments

There are no const-qualified compound literals in the question.
True but the implication is that string literals are stored in read-only memory, and 6.5.2.5 p 13 implies this as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.