I am working on a project with existing code which uses mainly C++ but with c-style strings. Take the following:
#include <iostream>
int main(int argc, char *argv[])
{
char* myString = "this is a test";
myString = "this is a very very very very very very very very very very very long string";
cout << myString << endl;
return 0;
}
This compiles and runs fine with the output being the long string.
However I don’t understand WHY it works. My understanding is that
char* myString
is a pointer to an area of memory big enough to hold the string literal “this is a test”. If that’s the case, then how am I able to then store a much longer string in the same location? I expected it to crash when doing this due to trying to cram a long string into a space set aside for the shorter one.
Obviously there’s a basic misunderstanding of what’s going on here so I appreciate any help understanding this.
You’re not changing the content of the memory, you’re changing the value of the pointer to point to a different area of memory which holds
"this is a very very very very very very very very very very very long string".Note that
char* myStringonly allocates enough bytes for the pointer (usually 4 or 8 bytes). When you dochar* myString = "this is a test";, what actually happened was that before your program even started, the compiler allocated space in the executable image and put"this is a test"in that memory. Then when you dochar* myString = "this is a test";what it actually does is just allocate enough bytes for the pointer, and make the pointer point to that memory it had already allocated at compile time, in the executable.So if you like diagrams:
Then