-2

I was trying to make a function that removes the string terminator and adds a newline character instead to a string. The way i do it leads to a segfault. And i am unable to wrap my head around why my string is immutable and how to make it work with my implementation. Thanks a lot for any help.

int main () {
    char* value = "message";
    value[7] = '\n';
    int success = write(1, value, 7);
    if (success == -1) {
        printf("write failed");
    }
}
jww
  • 97,681
  • 90
  • 411
  • 885
Anindya
  • 3
  • 3
  • `"message"` (what your `value` points to) is an array of 8 **read-only** char. You cannot change any of them. Copy them to a local array (as suggested by user3121023) to be able to change them. – pmg Sep 25 '18 at 21:33
  • You should get a warning from GCC using `-Wall` (or maybe `-Wextra`). I don't recall if microsoft compilers warn about it. – jww Sep 25 '18 at 21:33
  • To over-simply the problem, `value` is pointing to a segment of your program memory that is read-only. @user3121023 's suggestion has you instead create an array that contains the string and can be modified. – Christian Gibbons Sep 25 '18 at 21:33
  • 2
    Where are all of these zillion of dupes? – Eugene Sh. Sep 25 '18 at 21:33
  • 1
    [Why do I get a segmentation fault when writing to a string initialized with “char \*s” but not “char s\[\]”?](https://stackoverflow.com/q/164194/608639), [Modifying String Literal](https://stackoverflow.com/q/5464183), [Why is my char* writable and sometimes read only in C++](https://stackoverflow.com/q/2241834), [Segmentation fault reversing a string literal](https://stackoverflow.com/q/3172075), [If char*s are read only, why can I overwrite them?](https://stackoverflow.com/q/44294649), [Why are C string literals read-only?](https://softwareengineering.stackexchange.com/q/294748), etc. – jww Sep 25 '18 at 21:37
  • 1
    Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](https://stackoverflow.com/q/164194/608639) – jww Sep 26 '18 at 00:51

1 Answers1

1

C strings are immutable, effectively char const[] that only look like char [] for strange historical reasons.

If you want a mutable string, initialize a char array from a string literal:

char value[] = "message"; //autosized
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
  • 1
    "C strings are immutable" --> Do you mean "_string literals_ are immutable"? In detail, even _string literals_ are changeable - maybe. To attempt to change them is UB - it might work, might not. – chux - Reinstate Monica Sep 26 '18 at 01:55