Pointers To Const Char

狂风中的少年 提交于 2020-01-14 07:23:12

问题


The following code points to the first character in a char array available in read-only memory. Is that right?:

const char * ptr = "String one";

Now when ptr starts to point at another memory location:

ptr = "String two";

What happens to the first char array? Is that memory location freed when the execution ends?


回答1:


The standard only says that string literals have static storage duration, which means that the lifetime of the variable is until the program ends and it is initialized when the program starts. The relevant section in the C11 draft standard is 6.4.5 paragraph 6:

[...] The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence. [...]

It could be in read only memory and probably is but that is implementation defined. It does not need to be freed, only memory that is dynamically allocated via malloc needs a subsequent call to free.

If I use this program:

int main()
{
    const char * ptr = "String one";

    return 0;   
}

and we build it with gcc and then use objdump:

objdump -s -j .rodata a.out

We will find that in this case it is indeed stored in the read only data section:

Contents of section .rodata:
  400580 01000200 53747269 6e67206f 6e6500    ....String one. 

You can run it yourself here



来源:https://stackoverflow.com/questions/18003537/pointers-to-const-char

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