0

Why does the following code gives me Exception has occurred. Segmentation fault

char* someString = "original string";
someString[1] = 'O';
user97662
  • 942
  • 1
  • 10
  • 29
  • This declaration creates a char pointer, pointing to a const string. It will work if you instead declare with for example `char someString[20] = "original string";` – Klas-Kenny Dec 01 '21 at 12:30
  • 2
    String literals are read-only. See [C11 6.4.5p7](https://port70.net/~nsz/c/c11/n1570.html#6.4.5): "If the program attempts to modify such an array, the behavior is undefined." – pmg Dec 01 '21 at 12:30
  • In C all literal strings (like `"original string"`) are really **non-modifiable** arrays of characters, including the null-terminator. Attempting to modify a literal string leads to *undefined behavior*. That's why you should make it a habit to always use `const char *` for pointers to literal strings. – Some programmer dude Dec 01 '21 at 12:31
  • user97662, Note: `someString[1] = 'O';` _might_ work. Might not. It is undefined. Anything is allowed. Code is not required to seg. fault. – chux - Reinstate Monica Dec 01 '21 at 12:56
  • @Klas-Kenny `"original string"` is not a [const string](https://stackoverflow.com/questions/70184192/why-cant-i-change-individual-char-of-a-string-pointer-in-c#comment124066652_70184192) - its type is not `const` anything. Yet changes to a _string literal_ should not be attempted is good advice. Good to treat it as if is was a `const` _string_. – chux - Reinstate Monica Dec 01 '21 at 13:00

0 Answers0