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

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

    Arrays are stored in cml (i.e contiguous memory locations) depending of their scope type. For example global (static) arrays would be saved in the Block Started by Symbol (bbs) which is a part of the data segment, while local are created as a stack in the computer memory. It is a string, because each element from the array points to its next, forming sequence of characters, which forms the string. editing according to the new changes from the question Doing so:

    char str[] = "Hello World";
    

    You do:

    char str[] = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '\0'};
    

    Since the last character is '\0' / NULL / 0 You don't fill information into the last segnificent block of memory, where the data type is stored. In that case, you will terminate the string and you won't receive leaks. Thats just how C handles char arrays and especially strings. They are null-terminated strings. A lot of functions like strlen works only if there is a null terminator.

    Also if you use dynamicly created arrays they will be stored in the heap. As i know the heap is nothing much, basically it provides an environment for allocation and manages the memory for that purpose.

提交回复
热议问题