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
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.