When we can or cannot modify String Literals [duplicate]

我是研究僧i 提交于 2019-12-31 07:42:06

问题


#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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!