简体   繁体   中英

Why doesn't this program segfault?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM