2

    char *s1 = "emma";

    char *s2 = s1;

    s2[0] = toupper(s2[0]);

    printf("%s\n", s2);
    printf("%s\n", s1);

I am messing and studying with pointers but i don't quite understand why i'm getting a segmentation error here. I know that toupper function requires a char but isn't 0'th element of string s2 a char? I know it's a pointer but it's pointing at a char right? What's the case here?

  • 2
    You are trying to modify a `string literal` stored in `read only` memory area , which results in UB. Maybe make a copy of `s1` using `strdup()` , and modify that instead? – alex01011 Dec 12 '20 at 18:00
  • 2
    Also note that s2, points to s1. Therefore is not a copy of s1. – alex01011 Dec 12 '20 at 18:01
  • 1
    Ah so i can't modify predefined strings. Didn't know that thank you. And could you eleborate on whats UB? –  Dec 12 '20 at 18:02
  • 1
    `UB` stands for `Undefined Behavior` , as for your statement, *I can't modify predefined strings*, I suggest you check out this post , https://stackoverflow.com/questions/12795850/string-literals-pointer-vs-char-array – alex01011 Dec 12 '20 at 18:04
  • 2
    "I know that toupper function requires a char" --> detail: `toupper()` expects an `int` with a value in the `unsigned char` range or `EOF` - else UB. – chux - Reinstate Monica Dec 12 '20 at 18:06

1 Answers1

2

i don't quite understand why i'm getting a segmentation error here.

Code attempts to modify a string literal. That is UB. Make a copy.

UB: Undefined behavior - might work, might fail in obvious or bizarre ways.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256