: I was only half paying attention. Yes, line 3 might not behave as expected. You probably know this already, but I'm explaining for my own benefit as much as anything! The array initialisation in line 2 creates an array on the stack, of size strlen("this is a string you can modify")+1
, and copies the characters in the string literal into the array. Line 1 assigns the address of the string literal to p
is therefore an array of non-const char
s that can be modified and line 3 is fine. p
points to the actual string literal, which is an array of non-modifiable char
s and so line 4 invokes undefined behaviour (on my OS the literal is in the text section of the executable, which can't be modified, but that's an implementation detail).
I agree that the code shouldn't be valid; if string literals in C had type const char  instead of being "non-modifiable char"  the problem wouldn't exist. Bjarne Stroustrup's doing an interesting series of articles in the C/C++ Users Journal at the moment about C/C++ compatibility and why C++ retains this sort of gotcha from C, rather than fixing the mistake and abandoning compatibility.