0

I've tried this code snippet to assign '\0' to the last character of a C string

char *words = "words";
words[4] = '\0';

why is line 2 causes segmentation fault?

chendoy
  • 155
  • 1
  • 2
  • 12
  • 1
    The data `words` points to is *read-only*. When using pointers to literal strings, some programmers like to help themselves with `const`, as in `char const *words = "words";` – pmg Mar 05 '19 at 18:20
  • 2
    You're not supposed to modify a string literal. Any attempt to do so leads to undefined behaviour. One version of 'undefined behaviour' is that your code crashes because you attempt to modify read-only memory. There are many other possible behaviours. Don't do it. It only leads to trouble. If you must modify the string, make sure you have a modifiable array: `char words[] = "words";` — and now you can write `words[4] = '\0';` without danger. – Jonathan Leffler Mar 05 '19 at 18:23
  • @ChenDoytshman: String literals are intended to be immutable, and most platforms will store them in read-only memory (yours obviously does, which is why you got the segfault). However, not all platforms do, and the behavior is on trying to modify a literal is left undefined by the language standard. If you intend to modify the string, declare it as an *array* of `char` - `char words[N] = "words";`, where `N` is large enough to store whatever string you want to put there. If you declare a pointer to a literal, best practice is to declare it `const` - `const char *words = "words";`. – John Bode Mar 05 '19 at 18:29
  • @GenoChen: In what way is `char*` immutable? – Scott Hunter Mar 05 '19 at 20:32

1 Answers1

0

You didn't allocate the space for "words" (you only allocated the pointer to it), so (apparently) it has been placed some where you are not allowed to modify.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • `"words"` itself (string literal) is an array of char. Depending on OP's objectives there may be no need to allocate any memory. – pmg Mar 05 '19 at 18:24
  • @pmg: My point was that since OP didn't allocate it, it was allocated for him, and thus is subject to whatever constraints were placed on it by that allocation. – Scott Hunter Mar 05 '19 at 20:34