为什么当我写超出数组的末尾时我得不到分段错误? [英] Why don't I get a segmentation fault when I write beyond the end of an array?

查看:150
本文介绍了为什么当我写超出数组的末尾时我得不到分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在编译时不会出错?

why is this not giving error when I compile?

#include <iostream>
using namespace std;

int main()
{
    int *a = new int[2];
    // int a[2]; // even this is not giving error
    a[0] = 0;
    a[1] = 1;
    a[2] = 2;
    a[3] = 3;
    a[100] = 4;
    int b;

    return 0;
}

可以解释为什么会发生这种情况。
提前感谢。)

can someone explain why this is happening. Thanks in advance.)

推荐答案

我猜你是来自Java还是Java类语言其中一旦你走出数组的边界,你得到数组索引超出范围异常。

I'm guessing you're coming from Java or a Java-like language where once you step out of the boundary of an array, you get the "array index out of bounds" exception.

好吧,C期望更多从你;它节省了你要求的空间,但它不检查,看看你是否超出了保存的空间的边界。一旦你这样做,如上所述,程序有可怕的未定义的行为。

Well, C expects more from you; it saves up the space you ask for, but it doesn't check to see if you're going outside the boundary of that saved up space. Once you do that as mentioned above, the program has that dreaded undefined behavior.

记住,如果你有一个错误在你的程序,似乎找到它,当你去过代码/调试它,一切似乎确定,有一个很好的机会,你是超越界限,并访问一个未分配的地方。

And remember for the future that if you have a bug in your program and you can't seem to find it, and when you go over the code/debug it, everything seems OK, there is a good chance you're "out of bounds" and accessing an unallocated place.

这篇关于为什么当我写超出数组的末尾时我得不到分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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