Where are literal strings placed and why can I return pointers to them?

孤人 提交于 2019-12-20 05:36:10

问题


I stumbled upon this function in an answer to this question:

/* Note: I've formatted the code for readability. */
const char * getString() {
    const char *x = "abcstring";
    return x;
}

I was surprised to discover that returning a pointer to the literal string worked, and didn't segfault like I thought it would. I always assumed that literals were pushed on to the stack or put in some other temporary memory, but where limited to the scope of the function. But here it seems that they are more static than I had imagined. Are they then put into something sort of string pool that's global to the entire executable?

Also, is it the same thing if I pass a string literal as a parameter to a function? For example:

/* Where is the string literal in this example being placed? */
myfunc(value1, value2, "rainbowdash");

I hope someone can enlighten me. Thanks in advance! :)


回答1:


In C, string literals have static storage duration. Your code is logically equivalent to:

const char * getString() {
    static const char literal[] = "abcstring";
    const char *x = literal;
    return x;
}

with the exception that in the version with the string literal, the storage for the string could overlap with the storage of other string literals.




回答2:


As an addendum to most of the other answers, you can look at the assembler the compiler generates (e.g. by passing -S to GCC) to see how they are stored. Putting your function into a file by itself, we find that GCC basically generates (I've removed some irrelevant stuff):

.section        .rodata
.LC0:
        .string "abcstring"
        .text

        .globl  getString
        .type   getString, @function
getString:
        # load the address of ".LC0" which is the start of the "abcstring"
        movl    $.LC0, %eax 
        ret

So the string is stored in the .rodata section ("read-only data"), not on the stack and so it has a "global" address (and is always in scope).

Similarly, the string literal in myfunc("thisisastring") is also placed into a .rodata section, and is not on the stack.




回答3:


It varies per ABI, but on x86 they're in static memory/DATA page, pointed to by the DS register.



来源:https://stackoverflow.com/questions/11060504/where-are-literal-strings-placed-and-why-can-i-return-pointers-to-them

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