Possible Duplicate:
getting segmentation fault in a small c program
Here’s my code:
char *const p1 = "john";
p1[2] = 'z'; //crashes
printf("%s\n", p1);
I know p1 is a “read-only” variable, but I thought I could still modify the string (“john” ). I appreciate any tips or advice.
You cannot safely modify string literals, even if the pointer doesn’t look
const. They will often be allocated in read-only memory, hence your crashes – and when they’re not in read-only memory modifying them can have unexpected consequences.If you copy to an array this should work: