Does array initialization with a string literal cause two memory storage? [duplicate]

早过忘川 提交于 2021-01-28 06:13:17

问题


int main()
{
    char a[] = "123454321";
}

"123454321" is a string literal and a string literal sets aside memory storage. a is defined by the statement which also causes memory storage. That is, this simple statement char a[] = "123454321"; causes two memory storage, one is for a and the other is for "123454321". Is it right?


回答1:


Yes, that's right.

Note that the object on the right of the = is not a string literal as such; it's an initialisation expression and the compiler is under no obligation to store it as though it were a string. It might break it up into pieces, or emit a series of immediate stores instead of copying the initial value, or even (in theory) emit code which decompresses a shortened version of the initial data. But however it is compiled, some memory will be occupied.

If it the compiler does choose to store the initial value as a string, that value will need to be immutable so it may be placed in read-only memory and/or be shared with a string literal with the same value. a, on the other hand, is mutable and may be altered. So clearly it must have its own memory.

Finally, there is one case in which the compiler might not reserve ant space at all. It might optimise away either or both the unused array and the initial value if it can prove that no visible changes will result from the removal, as would be possible with the sample code in your question.



来源:https://stackoverflow.com/questions/65803496/does-array-initialization-with-a-string-literal-cause-two-memory-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!