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

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

    C does not have garbage collection, so if you forget to deallocate allocated memory with the proper deallocator, you get a memory leak.
    While sometimes a conservative garbage collector like the Boehm collector is used, that causes lots of extra headaches.

    Now, there are four types of memory in C:

    • static memory: This is valid from start to end. It comes in flavors logically read-only (writing is Undefined Behavior) and writeable.
    • thread-local memory: Similar to static memory, but distinct for each thread. This is new-fangled stuff, like all threading support.
    • automatic memory: Everything on the stack. It is automatically freed by leaving the block.
    • dynamic memory: What malloc, calloc, realloc and the like return on request. Do not forget to free resp. using another appropriate deallocator.

    Your example uses automatic memory for local_arr and leaves the implementation free to initialize it to the provided literal whichever way is most efficient.

    char local_arr[] = "I am here";
    

    That can mean, inter alia:

    • Using memcpy/strcpy and putting the literal into static memory.
    • Constructing the array on the stack by pushing the parts, thus putting it into the executed instructions.
    • Anything else deemed opportune.

    Also of interest, C constant literals have no identity, so can share space.
    Anyway, using the as-if rule, many times static (and even dynamic / automatic) variables can be optimized away.

提交回复
热议问题