Is a string literal in c++ created in static memory and destroyed only when the program exits?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- how to split a list into a given number of sub-lis
- thread_local variables initialization
相关文章
- JSP String formatting Truncate
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
Yes, string literals are valid for the entire duration of the program, even during the destruction of static objects.
2.13.4/1 in the Standard says
The Standard says of 'static storage duration' in 3.7.1/1:
Well ... Yes. They sort of have to be; the information that makes up the sequence of characters in each string has to be somewhere. If they were to be allocated dynamically and then initialized, where would the information used to to the initialization reside? Thus, it's more efficient to simply make the strings static, so that they are always available and valid once the program is done loading.
Where it's created is an implementation decision by the compiler writer, really. Most likely, string literals will be stored in read-only segments of memory since they never change.
In the old compiler days, you used to have static data like these literals, and global but changeable data. These were stored in the TEXT (code) segment and DATA (initialised data) segment.
Even when you have code like
char *x = "hello";
, thehello
string itself is stored in read-only memory while the variablex
is on the stack (or elsewhere in writeable memory if it's a global).x
just gets set to the address of thehello
string. This allows all sorts of tricky things like string folding, so that "invalid option" (0x1000) and "valid option" (0x1002) can use the same memory block as follows:Keep in mind I don't mean read-only memory in terms of ROM, just memory that's dedicated to storing unchangeable stuff (which may be marked really read-only by the OS).
They're also never destroyed until
main()
exits.String literals are stored in read-only segments of memory