Thursday, June 24, 2010

Is a string literal in c++ created in static memory?

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 BSS (initialized data) segment.

Even when you have code like char *x = "hello";, the hello string is stored in read-only memory while the variable x is on the stack (or writable memory at global scope). x just gets set to the address of the hello 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:

0x1000 invalid option\0
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.

Source: http://stackoverflow.com/questions/349025/is-a-string-literal-in-c-created-in-static-memory

No comments: