为什么没有这个程序段错误? [英] Why doesn't this program segfault?

查看:142
本文介绍了为什么没有这个程序段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是什么原因导致输出你好当我启用GCC -O?难道不应该仍然段错误(根据该维基)?

 %的猫segv.c
#包括LT&;&stdio.h中GT;
诠释的main()
{
    的char * s =你好;
    S [0] ='Y';
    看跌期权(S);
    返回0;
}
GCC%和segv.c功放;&安培; ./a.out
zsh的:分段错误./a.out
GCC%-O segv.c&放大器;&安培; ./a.out
你好


解决方案

它的未定义行为(可能会崩溃,可能不会做任何等)来更改字符串文字。很好的解释了Ç常见问题解答


  

6.4.5 / 6


  
  

有unspeci网络编辑这些阵列是否提供了不同的
  元素具有适当的值。如果程序试图
  修改这样的阵列,该行为是理解过程网络定义。


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.

这篇关于为什么没有这个程序段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆