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

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

    String Literals are stored in static area. When you copy string literals to a local variable, there will be two copies: static area and stack. The copy in static area will not be deleted. There is no GC in C. But if you use a pointer in a function, you can access the string.

    #include 
    
    char *returnStr()
    {
        char *p="hello world!";
        return p;
    }
    
    char *returnStr2()
    {
        char p[]="hello world!";
        return p;
    }
    int main()
    {
        char *str=NULL;
        char *str2=NULL;
        str=returnStr();
        str2 = returnStr2();
        printf("%s\n", str);
        printf("%s\n", str2);
        getchar();
        return 0;
    }
    

    So in the first function, it will print string because it uses a pointer. In the second function, the string in stack will be deleted so it will print garbage.

提交回复
热议问题