1

I'm a little bit confused with pointers at the moment, could someone explain to me the reason why attempting to change a char** with strcpy() causes a segmentation fault?

void *change_string(char **string) {
 char *add = "Changed!";
 strcpy(*string, add);
 return 0;
}

int main() {
 char *p = "Original-";
 change_string(&p);
 printf("%s",p);
}
mnille
  • 1,320
  • 4
  • 15
  • 19
tim
  • 33
  • 3

1 Answers1

1

Your pointer p points to a string literal and you modify that string when you call strcpy(3). Modifying a string literal is undefined behavior.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229
blatinox
  • 783
  • 5
  • 18