CodexBloom - Programming Q&A Platform

Undefined behavior when modifying string literals in C

👀 Views: 64 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-04
c string-literals undefined-behavior C

Quick question that's been bugging me - I'm working with a puzzling scenario 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 behavior: ``` 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! For context: I'm using C on Linux. Any ideas what could be causing this?