Undefined behavior when modifying string literals in C
I'm facing a puzzling issue while working with string literals in C. I expected to change the contents of a string literal, but I'm getting a segmentation fault. Here's a simplified version of what I have: ```c #include <stdio.h> int main() { char *str = "Hello, World!"; str[0] = 'h'; // Attempting to modify the string literal printf("%s\n", str); return 0; } ``` When I run this code, I get the following error: ``` Segmentation fault (core dumped) ``` From my understanding, string literals in C are stored in read-only memory, which is why trying to modify them leads to undefined behavior. However, I thought the compiler would at least give me a warning about this. I've tried using `char str[] = "Hello, World!";` instead, which seems to work fine: ```c #include <stdio.h> int main() { char str[] = "Hello, World!"; str[0] = 'h'; printf("%s\n", str); return 0; } ``` This approach allows me to modify the string without any issues, but I want to understand better why my first attempt fails so dramatically. Is there a standard way to handle string literals safely? Any insights would be appreciated!