String literals: Where do they go?

2018-12-31 01:02发布

I am interested in where string literals get allocated/stored.

I did find one intriguing answer here, saying:

Defining a string inline actually embeds the data in the program itself and cannot be changed (some compilers allow this by a smart trick, don't bother).

But, it had to do with C++, not to mention that it says not to bother.

I am bothering. =D

So my question is where and how is my string literal kept? Why should I not try to alter it? Does the implementation vary by platform? Does anyone care to elaborate on the "smart trick?"

8条回答
心情的温度
2楼-- · 2018-12-31 01:30

FYI, just backing up the other answers:

The standard: ISO/IEC 14882:2003 says:

2.13. String literals

  1. [...]An ordinary string literal has type “array of n const char” and static storage duration (3.7)

  2. Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation- defined. The effect of attempting to modify a string literal is undefined.

查看更多
其实,你不懂
3楼-- · 2018-12-31 01:32

A common technique is for string literals to be put in "read-only-data" section which gets mapped into the process space as read-only (which is why you can't change it).

It does vary by platform. For example, simpler chip architectures may not support read-only memory segments so the data segment will be writable.

Rather then try to figure out a trick to make string literals changeable (it will be highly dependent on your platform and could change over time), just use arrays:

char foo[] = "...";

The compiler will arrange for the array to get initialized from the literal and you can modify the array.

查看更多
登录 后发表回答