Why doesn't this program segfault?

烈酒焚心 提交于 2019-12-11 00:19:37

问题


What causes the output "Hello" when I enable -O for gcc ? Shouldn't it still segfault (according to this wiki) ?

% cat segv.c 
#include <stdio.h>
int main()
{
    char * s = "Hello";
    s[0] = 'Y';
    puts(s);
    return 0;
}
% gcc segv.c && ./a.out 
zsh: segmentation fault  ./a.out
% gcc -O segv.c && ./a.out 
Hello

回答1:


It's undefined behavior (might crash, might not do anything, etc) to change string literals. Well explained in a C FAQ.

6.4.5/6

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array,the behavior is undefined.



来源:https://stackoverflow.com/questions/7759162/why-doesnt-this-program-segfault

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