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


基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01