Home > Blockchain >  Where are arrays of string literals stored in C?
Where are arrays of string literals stored in C?

Time:10-06

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?

CodePudding user response:

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.

CodePudding user response:

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).

  •  Tags:  
  • c
  • Related