How are string literals compiled in C?

前端 未结 2 973
醉话见心
醉话见心 2020-12-11 23:05

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

相关标签:
2条回答
  • 2020-12-11 23:47

    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":

    • "an array of static storage duration and length just sufficient to contain the sequence" , which means that the literal will have a lifetime as long as the program.
    • "It is unspecified whether these arrays are distinct provided their elements have the appropriate value", which means the various "hello" literals in your example may or may not have the same address. You can't count on either behavior.
    • "If the program attempts to modify such an array, the behavior is undefined", which means that you can't change the string literal. One many platforms this is enforced (if you attempt to do so, the program will crash). On some platforms, the change may appear to work so you can't count on the bug being readily evident.
    0 讨论(0)
  • 2020-12-12 00:06

    Your understanding is correct, the data of "Hello" will be put in a RO segment, and its relative virtual address will be assigned to the pointers in the testX() functions.

    However, those are compiler-specific perspectives, the C standard doesn't care about them.

    EDIT: Per test3(), see τεκ's comment.

    0 讨论(0)
提交回复
热议问题