I’ve got the following code:
#include <iostream> using namespace std; int main() { char* a = 'foo'; char* b = 'bar'; a = b; cout << a << ', ' << b << endl; return 0; }
This compiles and works, ie. prints bar, bar. Now I would like to demonstrate that what goes on here is not copying a string. I would like to change b and show that a also changes. I came up with this simple code:
#include <iostream> using namespace std; int main() { char* a = 'foo'; char* b = 'bar'; a = b; b[1] = 'u'; // ← just this line added cout << a << ', ' << b << endl; return 0; }
…but it segfaults. Why? The interesting thing is that the following modification runs just fine:
#include <iostream> using namespace std; int main() { char* a = 'foo'; char b[] = 'bar'; // ← declaration changed here a = b; b[1] = 'u'; cout << a << ', ' << b << endl; return 0; }
Why doesn’t it segfault like the previous one? I guess I am missing some important difference between the pointer-style and the array-style string initialization.
You cannot change string constants, which is what you get when you use the pointer-to-literal syntax as in the first code samples.
See also this question: Is a string literal in c++ created in static memory?.