Is a string literal in C++ created in static memory and destroyed only when the program exits?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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';, thehellostring itself is stored in read-only memory while the variablexis on the stack (or elsewhere in writeable memory if it’s a global).xjust gets set to the address of thehellostring. 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.