2

Where are the string and char array stored?

int main ()
{
    int a = 0; //This should be stack
    char* p = "hello"; // why this is on the static?
    char k[10] = "hello"; //on the stack?
}

A textbook says that the char pointer (Char* a) will be stored on the static, from my understanding of "static memory", only these 2 will be stored on the static memory:

int a=0;// will on the static
int main()
{
    static xxxxx; //will on the static.
}

3
  • i think when you initialize a fixed size array using a string literal it's really a convenience syntax similar to initializing other kinds of fixed arrays using the curly brace syntax. but in other cases string literals live in static memory and you can have pointers that point to them. they last the duration of the program so you don't have to worry about deallocating them. Commented Jun 15, 2020 at 2:19
  • 2
    could you please change one of the variables named a to something else int a and char a[10] Commented Jun 15, 2020 at 2:24
  • there is no char* a. And char a[10] is an error since a is already defined as int . Commented Jun 15, 2020 at 2:25

2 Answers 2

6

By 6.7.8.2, the string "hello" in char *p = "hello" is string literal.
String literals are generally located in .rodata, to prevent modification. Also, global variable are located in .data section.

Sign up to request clarification or add additional context in comments.

3 Comments

And if on a Unix-like @SadSalad could use objdump -s -j .rodata a.out (or real program name in place of a.out) to view it.
So is that true string literals are stored in the static memory?
@SadSalad Yes, they are.
1

a will be on the stack. p itself will be on the stack. However, the data to which it points will be in a read-only section of memory (not the stack).

2 Comments

In every case "will" is "might" as it depends on the compiler's whims, as usual. They will be local variables scoped to that block, though.
Is read-only section = static memory? Or is there any relationship between them?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.