为什么这段代码不会导致段错误? [英] Why doesn't this code cause a segfault?

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

问题描述

为什么没有这个段错误?

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("
");

    return 0;
}

但当我在 for 循环中将 8 替换为 9 时,它确实如此.

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

注意:我在 32 位 crunchbang linux 上试用它

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.

希望这会有所帮助!

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

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