Search code examples
cstring-literals

Segmentation Fault in char pointer


I am getting segmentation fault when running the below code. What could be the reason for this error? Please help

int main()
{
    char *str2 = "Hello";
    str2[3] = 'J';
    printf("%s\n",str2);
    return 0;
}

Solution

  • It is a undefined behaviour because you are trying to modify the content of a string literal. A string literal mainly stored in a read only location. so you do not modify it, otherwise it is invoked undefined behaviour.

    C11 §6.4.5 String literals(Paragraph 7):

    It is unspecified whether these arrays are distinct provided their elements have the appropriate values.If the program attempts to modify a string literal of either form, the behavior is undefined"