为什么没有这个code会导致段错误? [英] Why doesn't this code cause a segfault?

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

问题描述

为什么没有这个段错误?

Why doesn't this segfault?

#include <stdio.h>
int main()
{
    int i;
    int arr[] = {1, 2, 3, 4};

    for(i=0;i<8;i++)
    {
        arr[i] = i;
        printf(" %d", arr[i]);
    }

    printf("\n");

    return 0;
}

但它确实,当我在9代替8环。

But it does when I replace 8 with 9 in the for loop.

请注意:我想它在32位的Linux crunchbang

Note: I am trying it on 32 bit crunchbang linux

推荐答案

从技术上讲,这一方案导致的 未定义行为 的,这意味着有绝对没有任何保证什么这个程序是允许这样做。它可以在原则上格式的硬盘,所有的朋友的电子邮件讨厌的消息,放火您的计算机,或成为有情和奴役人类。

Technically speaking, this program results in undefined behavior, meaning that there are absolutely no guarantees whatsoever about what this program is allowed to do. It could in principle format your hard drive, email nasty messages to all of your friends, set your computer on fire, or become sentient and enslave humanity.

在这种情况下,当n = 8恰好没有做什么坏事了不确定的行为,而未定义行为当n = 9导致段错误。两者都是该程序完全允许的行为,但不是在所有保证是便携式的。

In this case, the undefined behavior when n = 8 happens to not do anything bad, while the undefined behavior when n = 9 causes a segfault. Both are totally permissible behaviors for the program, but aren't at all guaranteed to be portable.

希望这有助于!

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

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