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
  • 49,413
  • 29
  • 133
  • 174
George Newton
  • 3,153
  • 7
  • 34
  • 49

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,822
  • 5
  • 49
  • 75