1

I am trying to change chars pointed to by a char pointer variable:

    char *test3 = "mutable";
    printf("Expected: mutable, Result: %s\n", test3);
    testt(test3);
    printf("Expected tutable, Result: %s\n", test3);

    void testt(char *s) {
        *s = 't'; // FAILS, I get Segmentation Fault Error
    }

Why does the above approach not work? Are chars pointed to by pointer variables immutable? If so, how would I modify the contents of the pointer variable?

herohuyongtao
  • 47,739
  • 25
  • 124
  • 164
George Newton
  • 3,033
  • 7
  • 30
  • 46

1 Answers1

3

That is because your char * points to a string literal and string literals are in almost every modern OS located in read-only storage.

Try copying it onto the stack:

char test3[] = "mutable";
Sergey L.
  • 21,074
  • 4
  • 47
  • 69