2

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
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
vikraman
  • 358
  • 7
  • 14
  • it says on platforms with memory protection. What platform are you on? – hroptatyr Oct 13 '11 at 19:09
  • 3
    Accept one of the answers explaining that this is "Undefined Behavior", which gives the compiler license to emit anything whatsoever for the entire program. But to answer your question, `"Hello"` is a `const char *`, which means its contents cannot be changed, so the optimizer is simply throwing away your attempt to modify it. (This is a perfectly valid optimization, since the modification attempt itself invokes Undefined Behavior.) – Nemo Oct 13 '11 at 19:15
  • No C string literals are not `const`; if they were, the assignment would be a constraint violation. (They are `const` in C++.) But yes, attempting to modify a string literal is undefined behavior. – Keith Thompson Oct 13 '11 at 19:37
  • @Keith: Thanks for the correction. I have been using C++ for the last few years so I forgot this detail. – Nemo Oct 13 '11 at 20:46
  • @hroptatyr I'm on amd64 linux! – vikraman Oct 14 '11 at 05:41
  • Whole lotta stuff in C is undefined behavior :-/ – vikraman Oct 14 '11 at 05:41

1 Answers1

12

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.

Community
  • 1
  • 1
cnicutar
  • 178,505
  • 25
  • 365
  • 392