Question

I know that string literal used in program gets storage in read only area for eg.

//global
const char *s="Hello World \n";

Here string literal "Hello World\n" gets storage in read only area of program . Now suppose I declare some literal in body of some function like

func1(char *name)
{
    const char *s="Hello World\n";
}

As local variables to function are stored on activation record of that function, is this the same case for string literals also? Again assume I call func1 from some function func2 as

func2()
{
    //code
    char *s="Mary\n";

    //call1
    func1(s);

    //call2
    func1("Charles");

    //code
}

Here above,in 1st call of func1 from func2, starting address of 's' is passed i.e. address of s[0], while in 2nd call I am not sure what does actually happens. Where does string literal "Charles" get storage. Whether some temperory is created by compiler and it's address is passed or something else happens? I found literals get storage in "read-only-data" section from String literals: Where do they go? but I am unclear about whether that happens only for global literals or for literals local to some function also. Any insight will be appreciable. Thank you.

Was it helpful?

Solution

A C string literal represents an array object of type char[len+1], where len is the length, plus 1 for the terminating '\0'. This array object has static storage duration, meaning that it exists for the entire execution of the program. This applies regardless of where the string literal appears.

The literal itself is an expression type char[len+1]. (In most but not all contexts, it will be implicitly converted to a char* value pointing to the first character.)

Compilers may optimize this by, for example, storing identical string literals just once, or by not storing them at all if they're never referenced.

If you write this:

const char *s="Hello World\n";

inside a function, the literal's meaning is as I described above. The pointer object s is initialized to point to the first character of the array object.

For historical reasons, string literals are not const in C, but attempting to modify the corresponding array object has undefined behavior. Declaring the pointer const, as you've done here, is not required, but it's an excellent idea.

OTHER TIPS

Where string literals (or rather, the character arrays they are compiled to) are located in memory is an implementation detail in the compiler, so if you're thinking about what the C standard guarantees, they could be in a number of places, and string literals used in different ways in the program could end up in different places.

But in practice most compilers will treat all string literals the same, and they will probably all end up in a read-only segment. So string literals used as function arguments, or used inside functions, will be stored in the same place as the "global" ones.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top