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

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

问题描述

为什么我编译的时候没有报错?

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天全站免登陆