Does garbage collection happen when we initialize a char array with a string literal in c?

后端 未结 5 1768
生来不讨喜
生来不讨喜 2021-01-25 12:20

When we write the following line of code in C,

      char local_arr[] = \"I am here\";

the literal \"I am here\" gets stored in the read only

5条回答
  •  無奈伤痛
    2021-01-25 12:25

    Not an answer (Deduplicator already has given a good one, I think), but maybe this'll illustrate your problem…

    Consider the following C code:

    #include 
    
    int main() {
        char foo[] = "012";
        /* I just do something with the array to not let the compiler
         * optimize it out entirely */
        for(char *p=foo; *p; ++p) {
            putchar(*p);
        }
        putchar('\n');
        return 0;
    }
    

    with the assembler output (with GCC on my machine):

    [...]
    .LC0:
        .string "012"
    [...]
    main:
    [...]
        movl    .LC0(%rip), %edi
    

    where you have a string in read-only memory (and that string will persist from program startup until exit). When I change the line initializing foo to

        char foo[] = "0123";
    

    GCC thinks it's worth doing it this way:

        movl    $858927408, (%rsp)  # write 858927408 long (4 bytes) to where the stack pointer points to
        movb    $0, 4(%rsp)         # write a 0 byte to the position 4 bytes after where the stack pointer points to
    

    858927408 is 0x33323130 (0x30 is the ASCII code for '0', 0x31 for '1' and so on); in the latter case the string isn't stored at read-only memory, it is stored in the instructions itself. In both cases, the array you eventually access is always on the stack. And you never have the ability to access the string literal in read-only memory in such a case, even if it exists.

    HTH

提交回复
热议问题