1

Why does modifying a pre-initialized string literal cause a segmentation fault? For example:

char *str = "Hello world";
str[0] = 'h'; 

When you initialize str to that string value, doesn't the compiler automatically allocate memory for that string constant, assign its starting location to str and free it upon program exit?

Ryan
  • 647
  • 2
  • 7
  • 17
  • The problem is that you shouldn't assign a string literal to a `char *`, it's deprecated, and your compiler should have generated a warning. See: http://stackoverflow.com/questions/13248399/hello-world-string-literal-can-be-assigned-to-char-type – Seth Oct 25 '13 at 22:50
  • if you want to read a bit more about this I'd take a look at https://www.securecoding.cert.org/confluence/display/seccode/STR30-C.+Do+not+attempt+to+modify+string+literals – jpw Oct 25 '13 at 22:51

1 Answers1

2

it is in a read only section of the process's address space because the string literal is a constant. (the str variable is not in read only space but it should be made to point to a valid writable location before you can use it the way you do.)

necromancer
  • 23,916
  • 22
  • 68
  • 115