[英]Why does the code work fine when I compile and run it even though I have not mentioned size of array?
class array {
public:
int arr[];
array() {
arr[0] = 1;
arr[100] = 2;
}
};
int main() {
array a;
cout << a.arr[0] << a.arr[100] << endl;
return 0;
}
I was expecting a segmentation fault on running the above code. 我在运行上面的代码时遇到分段错误。 However, it printed the correct output even though I have not mentioned array size.
但是,即使我没有提到数组大小,它也会打印正确的输出。 What is the reason for this?
这是什么原因呢?
What you get is Undefined Behavior. 您得到的是未定义行为。
Reading / Writing to unallocated memory does not automatically generate segmentation fault(s), but it is of course "bad practice" and should be avoided. 读/写未分配的内存不会自动生成分段错误,但是这当然是“不好的做法”,应避免使用。
It's impossible to tell exactly what will happen with such code, where that array will be addressed or what is already there and hence - Undefined Behavior. 无法确切说明此类代码将发生什么,该数组将在何处寻址或已经存在什么,因此-未定义行为。
Note : As mentioned by @juanchopanza, the code as it is is illegal in C++ because arr
is an incomplete type. 注意 :如@juanchopanza所述,由于
arr
是不完整的类型,因此该代码在C ++中是非法的。 Your compiler might (and obviously does) ignore this due to default settings, but a legal code that would demonstrate the same behavior is either: 您的编译器可能(并且显然确实)由于默认设置而忽略了这一点,但是可以证明相同行为的合法代码是:
class array {
public:
int *arr;
// ...
or 要么
class array {
public:
int arr[1];
// ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.