As far as I know , a string literal like "Hello"
is considered a char*
in C and a const char*
in C++ and for both languages the string literals are stored in read-only memory.(please correct me if I am wrong)
#include <stdio.h>
int main(void)
{
const char* c1;
const char* c2;
{
const char* source1 = "Hello";
c1 = source1;
const char source2[] = "Hi"; //isn't "Hi" in the same memory region as "Hello" ?
c2 = source2;
}
printf("c1 = %s\n", c1); // prints Hello
printf("c2 = %s\n", c2); // prints garbage
return 0;
}
Why source1 and source2 behave differently ?(compiled with gcc -std=c11 -W -O3)
strcpy
– Feldtsource2
version temporarily creates a local array on the stack, which has gone out of scope by the time you printc2
. If you want to mimic a string literal in a constant ("text") segment then use static instead of automatic storage. – Rarityconst char []
of whatever length. They decay intoconst char *
pointers. – Zamorasource1
andsource2
after they have gone out of scope invokes undefined behaviour. – Nan