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,328
  • 4
  • 16
  • 20
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
  • 730,956
  • 141
  • 904
  • 1,278
blatinox
  • 833
  • 6
  • 18