int main(){
char * ch = "hi";
char ** chh = &ch;
chh[100] = "hh";
}
What is chh[100] = "hh"
doing?
Where is the address of "hh"
being stored?
int main(){
char * ch = "hi";
char ** chh = &ch;
chh[100] = "hh";
}
What is chh[100] = "hh"
doing?
Where is the address of "hh"
being stored?
"hi"
and "hh"
are string literals, both of type const char[3]
, which decay into const char *
pointers to their 1st char
elements. The arrays are stored in the program's read-only static memory at compile-time.
At runtime, the address of "hi"
in that static memory is being stored in the ch
pointer (which is illegal in C++11 and later, since a non-const char*
pointer can't point to const char
data), then the address of ch
is being stored in the chh
pointer.
The statement chh[100]="hh"
is undefined behavior. chh
is pointing at ch
, which is stored on the stack of the calling thread. chh
is not a pointer to an array of 101+ char*
pointers, so indexing into the 100th slot of chh
is illegal (only index 0 is valid, as all variables can be treated as an array of 1 element). This code is reaching into stack memory that you don't own, and writing the address of "hh"
into the 100th slot of chh
is corrupting random memory on that stack (if it doesn't crash outright with an AccessViolation/SegFault).
The expression:
char* ch = "hi";
Is ill-formed because C++ forbids assigning string literals to char*
, the correct statement must be:
const char* ch = "hi";
The same goes for:
const char ** chh = &ch;
Both ch
and chh
must be const
qualified.
What is
chh[100]="hh"
doing?
Nothing it should be doing, chh[100]
is a pointer to memory that does not belong to chh
, this leads to undefined behavior.
Where is the address of
hh
being stored?
"hh"
is a string literal and is normally stored in read-only memory, that is the reason why C++ forbids its assignment to a non-const pointer, as atempts to change it will lead to, you guessed it, undefined behavior.
Don't confuse this with assignment to a char
array, that is legal because a copy of a string literal is assigned instead.
it tries to put a pointer to "hh" array on the stack at the location where chh+100 is pointing. you should never do that because you have no idea what will be happening (maybe this memory is used by an other bit of your code. you may trigger a segfault or a buffer overflow.