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

后端 未结 5 1739
生来不讨喜
生来不讨喜 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:43

    The program doesn't create a new string each time the loop hits it. There's only one string, which already exists, and the literal simply refers to that array.

    What happens is that when the compiler sees a regular string literal, it creates* a static array of char (C11 §6.4.5/6, C99 §6.4.5/5) containing the string's contents, and adds the array (or code to create it) to its output.*

    The only allocation that happens in the function is with char local_arr[] =..., which allocates enough space for a copy of the string's contents. Since it's a local, it is effectively released when control leaves the block that defined it. And due to the way most compilers implement automatic storage (even for arrays), it basically can't leak.

    * (Each literal might end up in its own array. Or, identical string literals might refer to the same array. Or, in some cases, the array might even be eliminated entirely. But that's all implementation-specific and/or optimization-related stuff, and is irrelevant for most well-defined programs.)

提交回复
热议问题