问题
#include<stdio.h>
int main ()
{
char *s="FIGHT" ;
printf("\n Whole string is %s ", s ); // Printing FIGHT -- this is fine
s[0]='L' ;
printf ("\n Now whole string is %s", s ); // Printing LIGHT -- My Question is how string literal constant is getting modified when it is being stored in read only memory .
}
Above Code is working fine on my system.
回答1:
TL;DR -- Never.
Any attempt to modify a string literal invokes undefined behavior.
To quote the C11
standard, chapter §6.4.5, String literals
[...]. If the program attempts to modify such an array, the behavior is undefined.
§ "Above Code is working fine on my system".
Yes, welcome to the world of undefined behavior, which includes working as (wrongly) expected.
来源:https://stackoverflow.com/questions/31659292/when-we-can-or-cannot-modify-string-literals