Apart from global and static data what else are allocated on Data segment ?
I remember reading somewhere that constant strings are also allocated on Data segment and same memory is used when a reference to same string constant is made
ex:
char* returnPointer()
{
char *p = "hello world"
//some code
return p;
}
void foo()
{
char *s = "hello world"
//some code
}
In the above code,
-
Does the memory for constant “hello world” allocated on Data segement or stack (just like any other local variable) ?
-
If allocated on Data segment, does both p and s point to same location ?
This is compiler-specific, but typically string literals live on the initialized data segment (often a special read-only portion of the initialized data segment). I don’t know of any architecture where string literals could plausibly live on the stack.
That’s up to the compiler.
When I compile your code using gcc 4.4.6, I see the following:
Here, the string literal is stored in a read-only data (
.rodata) section. The compiler is smart enough to realize that exactly the same literal is being used twice in the compilation unit, and it puts only one copy of it in.rodata.