cstringcs50toupper

C, toupper segmentation fault



    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?


Solution

  • 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.