当我们能够或不能修改字符串文字
#include 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 . }
以上代码在我的系统上运行正常。
TL; DR – 从不。
任何修改字符串文字的尝试都会调用未定义的行为 。
引用C11
标准,章节§6.4.5, 字符串文字
[…]。 如果程序试图修改此类数组,则行为未定义。
§ “以上代码在我的系统上运行正常” 。
是的,欢迎来到未定义行为的世界,其中包括(错误地)预期的工作 。