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

前端 未结 3 1058
有刺的猬
有刺的猬 2021-01-23 22:26

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 =         


        
3条回答
  •  甜味超标
    2021-01-23 22:55

    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.

提交回复
热议问题