char *s = "abcdf";
char s1[50] = "abcdf";
s1[0] = 'Q'; // Line 1
s[0] = 'P'; // Line 2
Here, s
is a guaranteed modifiable pointer that may be a global variable or local stack variable depending on whether you put that definition at program scope or inside a function. Sometime before you start using it, the compiler's required to arrange for the the address of the text "abcdf" to be loaded into s
. Typically in modern Operating Systems, "abcdf" itself will be in an area of read-only memory, where the "loader" that reads the program file into memory in preparation for execution tells the CPU itself to allow read but not write operations. So s
- which is modifiable - points to "abcdf" which is not.
s1
is a guaranteed modifiable array of 50 characters. Sometime before you start using it, the compiler's required to arrange for the text "abcdf" to be copied into that modifiable buffer. You can then modify that buffer safely as you do with s1[0] = 'Q'
.
s[0] = 'P'
uses the pointer s
to find the original non-modifiable / constant text "abcdf" in read-only memory, then tries to change it. As mentioned above, the CPU will typically have been configured to react by generating a CPU exception/trap/signal/interrupt (terminology differs with manufacturer). Your program will fail.