1

Possible Duplicate:
Why do I get a segmentation fault when writing to a string?

I have the following program:

char *s     = "abcdf";
char s1[50] = "abcdf";

s1[0] = 'Q';   // Line 1
s[0] = 'P';    // Line 2

Why Line 1 worked correctly and Line 2 caused the program to crash?

Community
  • 1
  • 1
ipkiss
  • 13,311
  • 33
  • 88
  • 123
  • 4
    Possible duplicate of [Why do I get a segmentation fault when writing to a string?](http://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string), [Is it possible to modify a string of char in C?](http://stackoverflow.com/questions/1011455/is-it-possible-to-modify-a-string-of-char-in-c/1011481), and [Modifying C string constants?](http://stackoverflow.com/questions/480555/modifying-c-string-constants). – In silico Apr 18 '12 at 02:37

2 Answers2

5

Line 2 points to the data section of your executable which is read-only, whereas in line 1, the program initializes s1 array with the given string. This is stored in stack, which you can modify.

JosephH
  • 8,465
  • 4
  • 34
  • 62
3
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.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252