How are string literals compiled in C? As per my understanding, in test1, the string "hello" is put in data segment by compiler and in the 2nd line p is assigned that hard-coded virtual address. Is this correct? and that there is no basic difference between how test1 works and how test2 works.
Some code:
#include <stdio.h>
test1();
test2();
test3();
main()
{
test1();
test2();
//test3();
}
test1()
{
char *p;
p="hello";
}
test2()
{
char *p="hello";
}
test3()
{
char *p;
strcpy(p,"hello");
}
any reference from C standard will be greatly appreciated, so that I can understand this thing in depth from compiler point of view.
From the C standard point of view there's no particular requirement about where the literal string will be placed. About the only requirements about the storage of string literals are in C99 6.4.5/5 "String literals":
"hello"
literals in your example may or may not have the same address. You can't count on either behavior.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With