为什么在超出数组末尾写入时不会出现分段错误

Why don#39;t I get a segmentation fault when I write beyond the end of an array?(为什么在超出数组末尾写入时不会出现分段错误?)
本文介绍了为什么在超出数组末尾写入时不会出现分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于为什么在超出数组末尾写入时不会出现分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)