In C, We can use char * to point at a string. Just like
char *s = "Hello";
.
As it be seen, Neither the variable is located dynamically on heap because there is no any dynamical functions like malloc, nor it is defined to point a certain other variable.
So my question is, Where is the literal string which variable [char *s] points to stored logically?
Is it stored in stack like any normal local variables? or, something like stack?
Actually, I am a graduate of Computer engineering department, but I haven't found and have been too much curious about how [char * string] works logically. It is a really great honor to ask right this one now.
The variable char* s is stored on the stack, assuming it's declared in a function body. If it is declared in a class, then it is stored wherever the object for the class is stored. If it is declared as a global, then it is stored in global memory.
In fact, any non-static and non-thread_local variable you declare in these three positions behave the same way, regardless of whether it is a primitive (i.e. int), an object (i.e. vector<int>), or a pointer (i.e. const char*).
If a variable is static, it is always stored in global space. If a variable is thread_local, each thread gets its own copy, and that copy will usually stored at the base of the stack for the corresponding thread.
The actual string "Hello", which s points to, is stored in a constant global space somewhere, usually the .data segment.
String literals have static storage duration. That means they exist for the whole lifetime of your program. They may be stored in a non-writable area, and they may overlap with other string literals. Two different instances of the same literal may or may not coincide.
It is up to your implementation (compiler/linker/etc). to make a decision that complies with those requirements.
There is nothing special about s, it's a pointer, it points somewhere. It has automatic storage duration just like any other local variable not declared static. What's “special” though is the string literal you are pointing to.
You can think of a string literal like "foo" as an unnamed global variable with some special constraints. These constraints are:
const