How are string literals compiled in C?

How are string literals compiled in C? In my understanding, in test1 the string "hello" is placed in the data segment by the compiler, and in the second line p, the hard code of the virtual address is assigned. It's right? and that there is no fundamental difference between how test1 works and how test2 works.

Some codes:

#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 the C standard would be greatly appreciated, so that I can understand this thing in depth from the point of view of the compiler.

+3
source share
2 answers

From the standard C point, there are no special requirements as to where the literal string will be placed. The only storage requirements for string literals refer to C99 6.4.5 / 5 "String literals":

  • " , , ", , , .
  • ", , ", , "hello" . .
  • " , undefined", , . ( , ). , , .
+4

, "Hello" RO, testX().

, , C .

EDIT: 3(), . τεκ.

+1

All Articles